Mockito is a JAVA-based mocking framework used for effective unit testing of various JAVA applications. It is used to mock interfaces to ensure dummy functionalities can be added to a mock interface in unit testing. This list of top Mockito interview questions should help you learn how to expertly create unit tests with Mockito and how to use its APIs simply and intuitively.
This tutorial is designed for both novice and expert-level Java developers who would like to improve the quality of their software through accurate unit testing and test-driven development. Once you complete this tutorial, you should gain adequate exposure to Mockito and take yourself to the next level of expertise.
Top 20 Mockito Interview Questions
Without further ado, here are the most commonly asked Mockito interview questions on the Mocking framework.
1. What is Mockito?
Mockito is an open-source testing framework for Java released under the MIT License. It allows developers to create mock objects used in automated unit tests to simulate the system’s behavior under test (SUT) without having to specify what developers expect from the system. It is often said that mock objects cause strict coupling between the test code and the system under test. However, Mockito tries to eliminate this by removing the requirement that the test code should behave as expected. Mockito provides some useful annotations that help developers reduce unused code.
2. List some benefits of Mockito?
Some of the benefits of Mockito include:
- Supports exceptions.
- Supports return values.
- Enables the creation of mock using annotation.
- The test code is not broken when users rename interface method names or reorder parameters.
- No need to manually write mock objects with Mockito.
3. Why do we need mocking?
There are a lot of benefits to mocking because it helps to test code that is isolated and makes unit testing much more repeatable and predictable.
Mocking is generally required when:
The component under test has dependencies not yet implemented or when the implementation is in progress.
Good examples include an API endpoint that will be available at a later date, but you have consumed the endpoint in your code via a dependency. Now that the actual API is available, you know what you should expect from the API. You can create a mock to test those kinds of integrations.
Component updates in the system.
You don’t want to update your DB with data that you have only imported for testing purposes. This might result in corruption of the data and/or performance issues, so you must have the data necessary to run the test and execute the tests. You may end up corrupting some of your database tables, and the availability of DB, while the test is being executed is another challenge.
DB calls could be mocked, so they do not cause problems for the component under test. There is no direct coupling between DB and the part you are testing.
4. What is the difference between doReturn and thenReturn?
Mockito provides two different syntaxes for creating stubs like doReturn and thenReturn. You can use these methods setup stubs to create or set up stubs. You can even use them interchangeably at times. Here is how they differ:
- Returning an empty string from a function that returns a function with an error is a type-safe way to set up a stub. The way that this works is that it checks against the type of return types that you want to stub.
- There is no significant difference between these two ways to set a stub on mock objects and mock objects because it will result in you calling the mock method before the stubbed response is returned.
For Spied objects, the thenReturn stub setup will not work because calling the real method before the stubbed response is returned can cause the Mock to crash. If we spy on a spy called spiedObject and we know that it has a method called testMethod which returns an integer, to stub it, you will need to use doReturn instead of thenReturn.
5. When and why should a spy be used?
Spy allows you to create partial mocks of a class object using Mockito. If you do not have a mock, you can use a spy to call the real methods. But spy allows you to verify that a method was actually called, how many times the method was called, and what arguments were used to call the method.
It gives you the flexibility to set up partial mocks of objects you want to mock. For example, you want to mock method1 and method2, but only method1 and method2 are mocked. If you have an object that has two methods – method1 and method2, you may want to call method1 and have method2 spy on it. Spy objects allow you to do this kind of setup easily.
The difference between making a mock and making a stub is that a mock is created from a type, not an instance of a class object. But a stub is created by using an actual instance of the class object to create a wrapper around it.
6. What is mocking in testing?
Mocking in Mockito is a quick and easy way to test the functionality of a web service or any other web application. They act like a mocker to pretend that you are the user and are actually performing a real service. These mock objects return the dummy data that is equivalent to what you enter into a function. Creating mock objects does not require you to connect to a database or to a file server to test functionality.
7. What is Hamcrest?
Hamcrest is a Java framework that allows programmers to write customized assertion matchers. The framework enables programmers to define rules that define what kind of test conditions a given test must satisfy. It allows developers to define match rules that are defined declaratively. Hamcrest allows you to write custom assertion matchers in Java. This makes it useful for UI validation, data filtering, writing flexible tests, etc. It can be used to test and debug mock objects using adapters. Hamcrest can be used with other Java and test engines such as JUnit and TestNG.
8. List some Mockito Annotations?
The most common Mockito annotations include:
- @Mock – Used to create and inject mocked instances.
- @Captor – Used to create an ArgumentCaptor.
- @Spy – Used to create a real object and spy on the actual object.
- @InjectMocks – Used to create a class object and insert its dependencies.
9. What is PowerMock?
PowerMock is a Java framework that allows you to mock Java classes and method calls. PowerMock extends other mock libraries that provide more powerful capabilities. It mocks methods that are not in use, such as static methods and functions. It also uses custom classloaders and bytecode manipulations to create mock classes that mock static methods, constructors, final classes, private methods, and more. It allows you to test code that is considered impossible to test.
10. What is EasyMock?
EasyMock allows the developers to quickly create and test virtual objects that are similar to the real ones by using a simple and automatic process that allows them to automatically generate their own mock objects from a given interface. It helps users create dynamic mock objects by automatically generating them using a dynamic object generator.
Here are some of the perks you get with EasyMock:
- Return value support
- Exception support
- Annotation support
- Order check support
- Refactoring scale
11. What is the difference between Assert and Verify in Mockito?
Both statements allow you to add validation logic to test methods in a test suite, but they differ in the following respect. The assert command is used to validate critical functionality. If something fails to satisfy the condition, the test method is stopped and marked as failed. However, if there are no more valid assertions, the test method will continue to run as normal. If it fails, all test methods in the test suite will be stopped and marked as failed.
The execute command for Verify command means that a test method continues to execute even when a test assertion fails to make an assertion that something is wrong. If the test method has failed, the result will be marked as failed, but the execution of the remaining statements in that test method will continue to work normally.
12. List some limitations of Mockito?
Here are some limitations of the Mockito:
- VM mocking is only possible with VMs supported by Objenesis.
- Requires Java version 6 plus to run.
- Cannot mock constructors or static methods.
- Cannot mock equals(), hashCode() methods.
13. What is the use of the mock() method in Mockito?
By using the mock() method, you can create and inject mock instances into your web apps. It gives you boilerplate commands to use while you work with mock instances. Another way to create an instance of a property is to use the annotations @mock (or similar).
14. What is ArgumentCaptor in Mockito?
ArgumentCaptor is a special class used to capture the argument values for any future assertions. It’s defined in the Mockito package and imported from it.
Here are some of the methods present in this class:
- ArgumentCaptor <U> forClass.
15. Why can’t static methods be mocked using Mockito?
Static methods are associated with the class itself and not any particular instance of that class. This means that all instances of that class use the same static method. A class has its own static method used by all its instances. All its methods call the same static method. Static methods are very much like procedural methods, but they are usually used in legacy software, like XML documents.
Mock libraries typically create mocks by dynamically creating new instances of an interface or an inheritance method during runtime. As static methods are not associated with any particular instance, it’s impossible to mock frameworks (like Mockito, easy mock, etc.) to mock static methods.
Frameworks that support static methods typically create bytecode from scratch and execute it to mock static methods.
16. What are Mocking/Stubbing default methods in Interface in Java 8?
Java 8 supports default methods in its interface, and Mockito allows developers to easily mock these methods (this support was introduced in Mockito 2). These methods can be mocked/stubbed like any other method or interface in a class or a method-set.
17. How can the order of stub invocations be verified in Mockito?
When you need to verify that other methods were called in the correct order on some objects, Mockito provides an InOrder interface that you can use to check the order in which mocks were called. During the test, you simply have to create an InOrder object that contains a list of mock objects on which you need to check the order in which methods were called (if there are multiple methods on the same mock and no other mock is needed then it’s sufficient to mention the mocked class only once).
18. What’s the need to verify that the mock was called?
If we set up a stub for something that is not being tested, it does not guarantee that it will actually be called. Verification matchers allow us to verify whether the stub we created was invoked or not, how many times the call was made, what arguments were used, etc. It enables us to verify the test setup and expect results more robustly.
19. What is a good testable code?
A few points about testable code that could be easily unit tested include:
- Reduced number of dependencies or tight coupling: Dependencies can be injected rather than instantiated directly.
- Less or Minimal usage of final classes and static methods: These often indicate code smells and were typically associated with the legacy code.
- Code adhering to SRP (Single Responsibility Principle): The class should not have several reasons to change. Adhering to SRP avoids classes establishing dependency on themselves and keeps your code clean and cohesive.
20. Which frameworks can support mocking Private and Static methods?
Frameworks like PowerMockito (Mockito framework extension), JMockit, etc., provide means to mock static and private methods.
The term “mock” is often used outside software development as a synonym for imitating or mimicking. It also means that a class can imitate an object that exists, even if that object is not the real one. It can be considered a stand-in, an imposter, or as frequently used in software development as a fake. Fakes are used to show that the classes we are testing depend on other classes that we have created, and as a result, fake classes are often used as substitutes for the classes that the user is testing.
When we learn to program, our objects are usually self-contained. We do not depend on external classes (or functions) or data access objects (DAOs) to work. Any hello world does not depend on other classes or scripts we write to learn a language. But in the real world, the software has dependencies. We have classes that depend on methods in our database, services that rely on our database, and many other things. Hopefully, these Mockito interview questions have helped you take your software development skills to the next level!