Table of contents
1.
Easy level questions
2.
Intermediate level questions
3.
Advanced level questions
4.
Conclusion
Last Updated: Jun 14, 2024
Medium

Mockito Interview Questions

Author Ashish Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Mockito is a java-based mocking framework that works with other testing frameworks like JUnit and TestNG. It uses the Java Reflection API internally and allows you to create service objects. Mock objects return dummy data while reducing external dependencies. It simplifies test development by mocking external dependencies and incorporates the mocks into the code under test.

mockito

If you are preparing for a Mockito interview in the future and are looking for a quick guide before your interview, then you have come to the right place.

This article will discuss the top 30 mockito interview questions, which consist of all types of mockito interview questions.

Now, let us briefly describe some helpful mockito interview questions.

Easy level questions

1. Define Spy in unit testing?

Ans: A spy is a form of partial mock that Mockito supports. We will take an existing object and "replace" only a portion of its methods while spying. It's useful when we have a large class and only want to duplicate a few methods (partial mocking).
 

2. What are the limitations of Mockito?

Ans: Some drawbacks of Mockito are:

  1. It can not mock static methods.
  2. Classes, constructors and private methods can not be mocked.
     

3. When is Mocking Essential?

Ans: It is necessary when:
🔺The component under test has dependencies that have not yet been implemented or are in the process of being implemented.
🔺A brilliant example is a REST API endpoint which will be available later, but you have used it in the code via a dependency.
🔺Because the actual implementation is still not public, you should know what can be the expected answer of that API. Mocks enable you to test the type of integration.
🔺The state of the system is updated by the component.


4. Define unit testing?

Ans: Unit testing confirms that individual units of code (usually functions) work independently as it is expected. Generally, you develop your own test cases to cover the code you wrote. Unit tests confirm that the component you built works perfectly when it operates independently.

Unit test is the piece of code developed by a developer that executes a specified functionality in the code under test.


5. Define Hamcrest?

Ans: Hamcrest is a well-known framework that allows us to design matcher objects. It is used to write software tests and unit tests in the Java programming language. Hamcrest is primarily used in combination with other unit testing frameworks like JUnit, jMockit, and Mockito. It allows for the creation of customized assertion matches, which allow match rules to be specified declaratively. Unit testing frameworks use these matches.


6. What are the benefits of Mockito?

Ans: Mockito has the following advantages:
🔺It can accept return values.
🔺It allows for exceptions.
🔺It supports the generation of mocks via annotation.
🔺Mockito eliminates the requirement for you to create mock objects on your own.


7. Can You Describe the Mockito Framework?

Ans: In Mockito, you should always check a specific class. The mock object is used to introduce the dependency in that class. So, if you have a service class, the Dao class is provided as a mockDao. This enables us to look at the method of that particular service class and determine whether or not it is performing as planned.

Assume the service class contains an updateObject Method. The method of updating is determined by Dao1 and Dao2. The goal here is to test only the updateObject function and not the Dao1 and Dao2 methods. As a result, we can construct a mockDao and return a mock object. This object is not in the database and was created from scratch. It simply checks to see if the updates are going on as planned. The below is the syntax for creating a Mock object:

private static codingninjas mockLedgerBook; //you create the mock object in the setup

setup()
{
mockLedgerBook = Mockito.mock(codingninjas.class);
}
//you call this mockLedgerBook as follows:

LedgerBook ledgerBook = new LedgerBook();
ledgerBook.setName("Coding ninjas");

Mockito.when(mockLedgerBook.findBookById(Mockito.anyLong()).
thenReturn(ledgerBook);
You can also try this code with Online Java Compiler
Run Code

 

8. What will you do if you want to ensure that a specific class method is called?

Ans: If it's a class's static method, we can use the verify to ensure it's being called.

If the method is an instance method, we can mock the object and then use verify with the mocked object to ensure that the function is called.


9. Can Mockito be used to mock private methods?

Ans: Mocking private or static methods is not supported by Mockito. To test private methods, we need to edit the code to change the access to protected (or package), and static/final methods should be avoided. Certain frameworks, such as PowerMock, do, provide mimicking for private and static functions.


10. Define Mockito inline?

Ans: From version 2.7.6, Mockito offers the 'mockito-inline' component, which enables inline mock creation without supplying the MockMaker extension file. Mockito supports complex mocking features as an option, such as copying final classes. To make this work, use a separate mechanism ("mock maker") that is considered experimental and hence turned off by default.

Intermediate level questions

11. Why Mockito.any is used?

Ans: Mockito.any(Class), Mockito.anyString, Mockito.anyLong, and other methods can be used to test that a method is being called with any argument instead of a specified parameter.


12. Justify "Mockito thread is safe".

Ans: Mockito works well with threads in healthy situations. You can run the tests in parallel to speed up the build. To test in parallel situations, you can also allow several threads to call methods on a shared mock. Consider using the timeout() function to test concurrency.

Mockito, on the other hand, is only thread-safe in healthy tests, tests in which no multiple threads are stubbing/verifying a shared mock. Stubbing or verifying a shared mock from several threads is NOT the right technique to test because it always results in irregular behavior. Mutable state + assertions in a multi-threaded context provide random results. If you stub/verify a shared mock across threads, you can encounter exceptions such as: WrongTypeOfReturnValue, etc.


13. Can I validate Tostring()?

Ans: No. You can, though, stub it. ToString() verification is not implemented because:

When debugging, the IDE uses the function toString()  on objects to print local variables and their contents, among other things. The verification of function toString() will most likely fail after debugging.

function toString() is the function that is used for logging or string concatenation. These invocations are normally insignificant, but they do affect the outcome of verification.


14. Define EasyMock.

Ans:  EasyMock is a framework for constructing mock objects for a specified interface by using Java reflection. It eliminates the need of the user to hand-write mock objects by employing a dynamic mock object generator.


15. Differentiate between Assert and Verify.

Ans: Assert: If the assert condition is true, the program flow will execute the next test step; else the execution will stop and no further test steps will be executed.

Verify: If the verify condition is true or incorrect, the test execution won't stop.


16. How can I use Mockito to mock void methods?

Ans: The collaborator in test cases will be the MyList class shown below.

List is a public class that extends AbstractList.

public class codingninjas extends AbstractList {

    @Override
    public void mockito(int index, String element) {
      // code
    }
}
You can also try this code with Online Java Compiler
Run Code

 

17. What is the difference between @Mock and @InjectMocks?

Ans: The Mock annotation generates mocks.

The InjectMocks function generates class objects. When the actual method body for a specific class needs to be run then use @InjectMocks.


18. Define Junits.

Ans: JUnit is a framework for unit testing in the Java programming language. JUnit has played an essential role in the evolution of test-driven development. JUnit is part of the xUnit family of unit testing frameworks, which started with SUnit.

At compilation time, JUnit is connected as a JAR.

JUnit created the concept of first testing and then coding to ensure that test data is set up and the expected output is defined before coding. This technique boosts program code productivity and stability while decreasing debugging time.


19. Define Spying in Mockito.

Ans: Mockito allows you to develop spy on real-world things. When a spy is performed, the actual method of the real object is invoked.

syntax:

//create an actual object on spy 
calcService = spy(calculator);

//perform operation on the real object 
Assert.assertEquals(mathApplication.add(20.0, 5.0),30.0,0);
You can also try this code with Online Java Compiler
Run Code

 

20. Define ArgumentCaptop in Mockito.

Ans: ArgumentCaptor is a class which is used to save the values of arguments for future assertions. This class is defined in the package org.mockito and can be imported from there.

Some of the methods in this class are as follows:

capture(), getValue(), getAllValues(), and ArgumentCaptor <U> forClass are all functions.

Html interview questions

Advanced level questions

21. When and why would a spy be used?

Ans: A spy is a form of partial mock that Mockito supports.

This simply means that there is a situation in which:

🔺When no mock is configured, any contact with spy calls the real methods. It still allows you to check interactions with the spied object, such as if a method was actually called, how many times the method was called, what parameters were used to call the method, etc.

🔺It gives you the option of creating partial mocks.

For example, suppose you have an object with two methods, method1 and method2, and you want method1 to be executed while method2 is mocked. This type of arrangement is provided by spies. In simple terms, the difference between a mock and a stub is that a mock is constructed from a type except for an instance, but a stub contains an actual instance of the class object.


22. Why can't Mockito be used to mock static methods?

Ans: Static methods are connected with the class, not with any single instance of the class. This indicates that all instances/objects of the class use the same static method instance.

Static methods are like procedural code and are commonly found in legacy systems.

Mock libraries normally generate mocks at runtime by dynamically creating instances via interfaces or inheritance, and because static methods are not connected with any particular instance, mocking frameworks (such as mockito, simple mock, and others).

Frameworks that enable static methods, such as PowerMock, use bytecode alteration at runtime to mock static methods.

Also see, jQuery interview questions 


23. Define PowerMock?

Ans: PowerMock is a Java framework used for unit testing. PowerMock framework builds on the features of other mock libraries. It mocks static methods, constructors, final classes, private methods, and more using a custom classloader and bytecode modification. It usually allows you to test code that is considered untestable.


24. In mockito, how do you mock a void method?

Ans: In Mockito, we can use a variety of methods to call a mock void method. We can choose one of the solutions based on our requirements.

🔻doNothing(): It Ignores the void method call.
🔻doAnswer(): When the void method is used, doAnswer() executes specific run-time or complex operations.
🔻Do Throw(): DoThrow() throws an exception when a mocked void function is called.
🔻doCallRealMethod(): Do not mock while calling the real method.


25. “Returning multiple values in response to numerous method calls”, explain.

Ans: Mockito supports three techniques for returning various values for multiple requests of the same stubbed method, as shown below:

▶️Using comma-separated values: This is compatible with thenReturn.

For example, let us try to create a consecutive stub for method - getGrade, which would return different values based on the sequence of iterations:

when(mockDatabaseImpl.getGrade(anyInt())).

thenReturn("A," "B," "C");
You can also try this code with Online Java Compiler
Run Code

 

This means that when the getGrade methods executed in the test method, the first iteration will return "A," the second will return "B," and so on.

▶️Consecutive thenReturn: This is a method that uses thenReturn statements in a chain. When chained calls are applied to the same example,

when(mockDatabaseImpl.getGrade(anyInt())).

thenReturn("A").

thenReturn("B").

thenReturn("C");
You can also try this code with Online Java Compiler
Run Code

 

▶️Consecutive doReturn: The final method is to use doReturn in the chained pattern.

doReturn("A").

doReturn("B").

doReturn("C").

when(mockDatabaseImpl).

getGrade(anyInt())
You can also try this code with Online Java Compiler
Run Code

 

26." Mocking/Stubbing Interface Default Methods in Java 8", Explain.

Ans: Mockito provides support for mocking such default methods with the help of  Java 8's implementation of default methods in Interface. 

These methods, like any other methods in a class or interface, can be mocked/stubbed.


27. In Mockito, how can the order of stub requests verify?

Ans: Mockito's "InOrder" interface can be used to verify the order in which mocks were called.

During the test, you simply set up / create an Inorder object if there are multiple methods on the same mock, there is no other mock that needs to be verified, then mentioning the mocked class only once is sufficient.


28. Can you give an example of using doNothing() for the void method?

@Test
public void test
	findByName() {
   doNothing();
	when(mockedUserRepository);

findByName(anyString());
   userService.findByName("coding ninjas");
   verify(mockedUserRepository, times(1));

   findByName("coding ninjas");
}
You can also try this code with Online Java Compiler
Run Code

 

29. Give an example of using doAnswer() for a void method.

@Test
public void testUpdateUser() {
  
    doAnswer(invocation -> {
      int Id = invocation. getArgument(0);
      String Name = invocation. getArgument(1);
      assertEquals(1, Id);
      assertEquals("coding ninjas", Name);
      return null;
}).when(mockedUserRepository).UpdateUser(anyInt(),anyString());

   userService.UpdateUser(1,"coding ninjas");
   verify(mockedUserRepository, times(1)).
   UpdateUser(1,"coding ninjas");
}
You can also try this code with Online Java Compiler
Run Code

 

30. How can I launch another method in a mock object?

 @Test
public void Coding ninjas() {
  	  
  	  User name = Mockito.mock(User.class);
    
    	Mockito.doCallRealMethod().when(name).add();
    	Mockito.doCallRealMethod().when(name).delete();
        
        name.delete().onConfirm();
      
     Mockito.verify(name).delete();
}
You can also try this code with Online Java Compiler
Run Code

Conclusion

In this article, we have discussed mockito interview questions in detail. We started with a basic introduction to mean stack, then we discussed some introductory mockito interview questions, intermediate mockito interview questions, and advanced mockito interview questions.

After reading about the mockito interview questions, are you not feeling excited to read/explore more articles on the topic of interview questions? Don't worry; Coding Ninjas has you covered. Other interview-related articles are Ansible interview questionsFlutter Interview QuestionsWeb API Interview Questions, Operating System Interview QuestionsWCF Interview QuestionsMachine Learning Interview QuestionsSQL Interview Questions, Production Support Interview Questions, and Selenium Interview Questions.


Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass