10 Mockito JUnit Interview Questions and Answers
Prepare for your next Java interview with our comprehensive guide on Mockito and JUnit, featuring common questions and detailed answers.
Prepare for your next Java interview with our comprehensive guide on Mockito and JUnit, featuring common questions and detailed answers.
Mockito is a popular mocking framework for unit tests in Java, particularly when used in conjunction with JUnit. It allows developers to create mock objects and define their behavior, making it easier to isolate the code being tested and ensure that unit tests are both reliable and maintainable. Mockito’s intuitive API and seamless integration with JUnit have made it a go-to tool for Java developers aiming to write clean, efficient, and effective tests.
This article provides a curated selection of interview questions focused on Mockito and JUnit, designed to help you demonstrate your proficiency in these essential testing tools. By working through these questions and understanding their answers, you’ll be better prepared to showcase your expertise and problem-solving abilities in technical interviews.
Mockito is a framework for Java that allows developers to create mock objects for testing. These mock objects simulate the behavior of real objects, making it easier to test interactions between components. Mockito is useful for isolating the unit being tested by providing mock dependencies, which helps verify behavior without relying on external systems.
JUnit is a testing framework for Java that provides the structure and annotations for writing and running tests. It allows developers to define test cases, group them into test suites, and execute them automatically. JUnit also provides assertions to check expected outcomes.
When used together, Mockito and JUnit enable developers to write comprehensive unit tests that are isolated and repeatable. Mockito creates mock objects and defines their behavior, while JUnit provides the framework to execute tests and verify results.
Example:
import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class ServiceTest { @Mock private Dependency dependency; @InjectMocks private Service service; public ServiceTest() { MockitoAnnotations.initMocks(this); } @Test public void testServiceMethod() { when(dependency.someMethod()).thenReturn("Mocked Result"); String result = service.serviceMethod(); assertEquals("Mocked Result", result); } }
Mockito is a framework for mocking objects in unit tests, allowing you to create mock objects and define their behavior. JUnit is a testing framework in Java. Together, they enable effective unit tests by mocking dependencies.
Example:
import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class MyServiceTest { @Mock private MyDependency myDependency; private MyService myService; @Before public void setUp() { MockitoAnnotations.initMocks(this); myService = new MyService(myDependency); } @Test public void testMyServiceMethod() { when(myDependency.someMethod()).thenReturn("Mocked Response"); String result = myService.myServiceMethod(); assertEquals("Mocked Response", result); } }
In this example, MyDependency
is a dependency of MyService
. Using Mockito, we create a mock of MyDependency
and define its behavior using when
and thenReturn
. This allows us to test MyService
in isolation, ensuring the test focuses on the unit of work without being affected by MyDependency
.
To verify that a method was called a specific number of times using Mockito, use the verify
method. This method specifies the mock object and the number of times the method should have been called.
Example:
import static org.mockito.Mockito.*; public class ExampleTest { @Test public void testMethodCallCount() { MyClass myClass = mock(MyClass.class); myClass.myMethod(); myClass.myMethod(); verify(myClass, times(2)).myMethod(); } }
In this example, we create a mock object of MyClass
and call myMethod
twice. We then use verify
to check that myMethod
was called exactly two times.
Argument matchers in Mockito specify flexible conditions for method arguments when stubbing or verifying interactions. This is useful when exact argument values are not known or important for the test. Mockito provides matchers like any()
, eq()
, and argThat()
.
Example:
import static org.mockito.Mockito.*; import static org.mockito.ArgumentMatchers.*; public class ArgumentMatcherExample { public static void main(String[] args) { List<String> mockedList = mock(List.class); when(mockedList.get(anyInt())).thenReturn("element"); mockedList.get(0); verify(mockedList).get(anyInt()); } }
In this example, anyInt()
is used to stub the get
method of a mocked List object, allowing it to return “element” for any integer argument. Similarly, anyInt()
is used to verify that get
was called with any integer argument.
Stubbing in Mockito defines the behavior of methods on mock objects. This isolates the class under test from its dependencies, ensuring tests are predictable and repeatable. When you stub a method, you specify what should be returned when that method is called.
Example:
import static org.mockito.Mockito.*; import org.junit.Test; import static org.junit.Assert.*; public class StubbingExampleTest { @Test public void testStubbing() { List<String> mockedList = mock(List.class); when(mockedList.get(0)).thenReturn("first element"); String result = mockedList.get(0); assertEquals("first element", result); } }
In this example, get(0)
of the mocked List
object is stubbed to return “first element”. When called, it returns the stubbed value, allowing the test to verify the expected behavior.
In Mockito, argument captors capture arguments passed to a mocked method for further assertions. This is useful for verifying the values passed to a method during testing. The ArgumentCaptor
class provides this functionality.
Example:
import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.ArgumentCaptor; public class ArgumentCaptorTest { @Test public void testArgumentCaptor() { List<String> mockedList = mock(List.class); mockedList.add("one"); mockedList.add("two"); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(mockedList, times(2)).add(argumentCaptor.capture()); List<String> capturedArguments = argumentCaptor.getAllValues(); assertEquals("one", capturedArguments.get(0)); assertEquals("two", capturedArguments.get(1)); } }
To handle exceptions thrown by mocked methods in Mockito tests, use the doThrow
method. This method specifies an exception to be thrown when a particular method is called on a mock object. You can then write your test to verify that the exception is handled as expected.
Example:
import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.Mockito; public class ExceptionHandlingTest { @Test(expected = RuntimeException.class) public void testExceptionHandling() { MyService myService = Mockito.mock(MyService.class); doThrow(new RuntimeException("Exception occurred")).when(myService).performAction(); myService.performAction(); } } class MyService { public void performAction() { // Method implementation } }
@Captor
annotation in Mockito with an example.The @Captor
annotation in Mockito creates an ArgumentCaptor
instance, allowing you to capture and inspect arguments passed to a method in a mock object. This is useful for verifying that the correct arguments are being passed during testing.
Example:
import static org.mockito.Mockito.*; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class ExampleTest { @Mock private List<String> mockedList; @InjectMocks private SomeService someService; @Captor private ArgumentCaptor<String> captor; @Test public void testCaptor() { MockitoAnnotations.openMocks(this); someService.addToList("test"); verify(mockedList).add(captor.capture()); assertEquals("test", captor.getValue()); } } class SomeService { private List<String> list; public SomeService(List<String> list) { this.list = list; } public void addToList(String item) { list.add(item); } }
In this example, @Captor
creates an ArgumentCaptor
for capturing the argument passed to the add
method of the mocked list. The verify
method ensures that add
was called with the correct argument.
InOrder
to verify the order of method calls on mocks. Provide an example.In Mockito, InOrder
verifies that certain methods on mocks are called in a specific order. This is useful when the order of operations is important to the functionality being tested. InOrder
allows you to create a sequence of method calls and verify that they occurred in that sequence.
Example:
import static org.mockito.Mockito.*; public class InOrderExample { public static void main(String[] args) { List<String> mockList = mock(List.class); mockList.add("first"); mockList.add("second"); InOrder inOrder = inOrder(mockList); inOrder.verify(mockList).add("first"); inOrder.verify(mockList).add("second"); } }
In this example, we create a mock list and perform two add
operations. Using InOrder
, we verify that add
was called first with “first” and then with “second”. If the order were different, the test would fail.
In Mockito, verifying that there were no interactions with a mock ensures that certain methods were not called during a test. This can validate that the code behaves as expected and does not perform unintended operations.
To verify no interactions with a mock, use the verifyNoInteractions
method. This checks that no methods have been called on the given mock object.
Example:
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class NoInteractionTest { @Test public void testNoInteraction() { MyService myServiceMock = Mockito.mock(MyService.class); verifyNoInteractions(myServiceMock); } }