Mockito is one of the most popular mocking frameworks for unit testing Java applications. As Java developers are increasingly adopting test-driven development practices, knowledge of Mockito is becoming indispensable for those preparing for technical interviews.
In this complete guide, we will explore some of the most common and critical Mockito interview questions that assess your understanding of mocking, stubbing, verification, and other key concepts. Whether you are a beginner looking to get started with Mockito or a seasoned professional prepping for your next big interview, this guide will help you master Mockito and ace those tough questions.
Why is Mockito Important for Interviews?
Mockito has become a fixture in Java developer interviews for several reasons
-
Isolation of units under test – By mocking dependencies, Mockito enables true unit testing where each test case focuses on one unit in isolation. This aligns with modern testing best practices.
-
Simulation of complex scenarios – Mockito makes it easy to mimic various complex scenarios like exceptions, varying outputs based on inputs etc. This helps test critical edge cases.
-
Readability and maintainability – Mockito promotes simple, readable test code by reducing boilerplate. Its syntax enforces clean tests that are easy to understand and update.
-
Skill assessment – Candidates’ ability to articulate Mockito concepts and implement mocking scenarios demonstrates in-depth understanding of testing principles.
Mastering Mockito signifies competency in unit testing Let’s now explore some key interview questions around it.
Basic Mockito Interview Questions
These fundamental questions check your understanding of why and how Mockito is used:
Q1. What is mocking and what are mock objects?
Mocking is the process of creating dummy implementations of real objects that can be used in place of dependencies during testing Mock objects simulate the public interface of the real objects they stand in for This allows isolating and testing application code without dealing with complex dependencies,
For example, instead of making an actual database connection, we can use a mock object that implements the same connection interface but contains simulated responses.
Q2. How is Mockito different from other mocking frameworks like EasyMock?
Some key differences between Mockito and EasyMock are:
-
Simpler syntax – Mockito uses a simple, compact API whereas EasyMock has a complex record-replay-verify model.
-
Readability – Mockito tests typically have a given-when-then structure that enhances readability.
-
Smart stubs – Mockito provides smarter stubbing with custom responses based on arguments. EasyMock requires switching to expects/andStubReturn model for this.
-
Built-in verification – Mockito verifies interactions automatically without having to specify expectation first.
-
Failure handling – Mockito reports all failures together after tests complete while EasyMock fails on first unmet expectation.
Q3. What are the benefits of using Mockito for unit testing?
Some key benefits of using Mockito are:
-
Avoiding external dependencies like databases, web services etc.
-
Simulating various scenarios like exceptions etc.
-
Facilitating test-driven development through readable and maintainable tests
-
Reducing boilerplate code needed to create and interact with mock objects
-
Simplifying testing of edge cases
-
Enabling isolation and independent testing of each part of the system
Q4. What are spies in Mockito and how are they different from mocks?
While mocks are fake objects that return configured responses, spies wrap existing real objects. Spies call the real methods by default unlike mocks which need explicit stubbing. Mocks are ideal for isolating testing while spies are useful when real behavior is needed in certain cases.
For example, we may want to spy on a real service object to assert that a specific method was called but allow normal processing of other methods. A mock would require stubbing all methods while a spy only requires configuring the method we want to verify.
Intermediate Mockito Questions
Let’s now look at some intermediate-level questions that assess how well you can apply Mockito concepts:
Q5. How do you verify that a specific method was called using Mockito?
We use Mockito’s verify() method to check if a mocked method was called. For example:
// Create mock List mockList = mock(List.class);// Call method on mockmockList.add("Test"); // Verify add() was called verify(mockList).add("Test");
This verifies that add()
was called on the mock with the argument “Test”. The test fails if add()
was not called.
Q6. How do you stub a mock to throw an exception in Mockito?
We can use Mockito’s thenThrow()
method to stub a mock to throw an exception like so:
// Create mockFileSystem mockFs = mock(FileSystem.class);// Stub method to throw exceptionwhen(mockFs.read("file.txt")).thenThrow(IOException.class);// Following will throw IOExceptionmockFs.read("file.txt");
This configures read() on the mock to throw an IOException when called with “file.txt” argument.
Q7. How do you validate arguments passed to a mocked method call in Mockito?
To validate arguments, we capture them using ArgumentCaptor like below:
// Create captor ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);// Capture argumentverify(mockList).add(captor.capture()); // Assert valueassertEquals("Test", captor.getValue());
Here we are capturing the string argument passed to add()
and then asserting it is equal to “Test”.
Q8. How do you configure multiple returns from the same method call?
We can stub a mock to return different values on consecutive calls using thenReturn()
like:
when(mockList.get(0)).thenReturn("Foo").thenReturn("Bar");// First call returns "Foo", second returns "Bar"String first = mockList.get(0); String second = mockList.get(0);
This configures the stub to return “Foo” first time get(0) is called, and “Bar” on second call.
Advanced Mockito Interview Questions
Finally, let’s look at some advanced Mockito questions that assess your deep expertise:
Q9. How do you verify that a mock method was called with arguments matching a custom predicate?
We can pass an argument matcher instead of actual values to verify()
using argThat()
:
// Call method mockList.add("Test");// Verify with custom argument matcher verify(mockList).add(argThat(str -> str.length() > 4));
This asserts that add() was called with a string argument longer than 4 characters.
Q10. How can you mock a static method using Mockito?
Mockito cannot mock static methods directly. We need to use PowerMockito along with Mockito to mock static methods.
@RunWith(PowerMockRunner.class)@PrepareForTest( UtilityClass.class)public class MyTest { @Before public void setUp() { mockStatic(UtilityClass.class); } @Test public void testStaticMethodMock() { // Now we can mock static method when(UtilityClass.staticMethod()).thenReturn(3); }}
First we prepare the class containing static method using @PrepareForTest
. Then we call mockStatic()
on the class to stub static methods.
Q11. How do you verify that no more interactions happened on a mock?
We can assert no more method calls occurred after our tests by calling verifyNoMoreInteractions()
:
verify(mockList).add("one");verify(mockList).add("two");// Assert no more interactions with mockListverifyNoMoreInteractions(mockList);
This passes if only the two verified methods were called on mockList and fails if any other method was called after our assertions.
Mockito is a critical skill for Java developers to demonstrate during interviews. This guide covers a wide range of Mockito questions that can assess your fundamental understanding as well as test advanced expertise around stubbing, verification and edge cases.
Preparing answers to these questions is an excellent way to get interview ready. You can also check out coding exercises around mocking complex scenarios to thoroughly sharpen your skills. Master these concepts and you’ll be able to tackle any Mockito questions that come your way!
Mockito Junit Interview Question and Answer for fresher and experienced with example | Code Decode
FAQ
What is Mockito and why it is used?
What is the difference between Mockito and JUnit?
What is the difference between PowerMock and Mockito?
What is the common question in a mock interview?