Java - Interview Questions and Answers on Junit and Mocking Frameworks

1. Which of the following  are usually automated and which are executed manually ?

Unit Test
Integration Test 

Ans. Unit Test are usually automated and Integration Tests are usually executed manually. 

2. What are Junits ?

Ans. Junt is the unit testing framework for Java.

3. Are Junits tested manually ?

Ans. No , they are executed automatically.

4. How to test whether the returns value of the method is expected ?

Ans. Using Assert.

5. Which package Assert belong to ?

Ans. java.unit

6. What happens if the assert doesn't evaluate to be true ?

Ans. Junit fails.

7. How to create a Junit to make sure that the tested method throws an exception ?

Ans. Using annotation Test with the argument as expected exception.

@Test (expected = Exception.class)

8. What should I do if I want to make sure that a particular method of a class is getting called ?

Ans. If its a static method of the class , we can use verify to make sure it's getting called.

If its an instance method , We can mock the object and then use verify with the mocked object to make sure that the method is getting called."

9. Name few Java Mocking frameworks ?

Ans. Mockito, PowerMock, EasyMock, JMock, JMockit

10. What is the use of Mockito.any ?

Ans. In case we need to verify that a method is being called with any argument and not a specific argument we can use Mockito.any(Class), Mockito.anyString, Mockito.anyLong etc.  

11. How should we ignore or avoid executing set of tests ?

Ans. We can remove @Test from the respective test so as to avoid its execution. Alternatively we can put @Ignore annotation on the Junit file if we want to ignore all tests in a particular file.

12. How can we test methods individually which are not visible or declared private ?

Ans. We can either increase their visibility and mark them with annotation @VisibleForTesting or can use reflection to individually test those methods.