Mockito Interview Questions

By | March 31, 2023

What is Mockito and how does it help in testing?

Mockito is a Java-based open-source testing framework used for creating mock objects in automated unit tests. It is used to simplify the testing of applications by allowing developers to easily create mock objects, which simulate the behavior of real objects in a controlled manner. Mockito is widely used in the industry for unit testing and is considered one of the most popular testing frameworks in Java.

Mockito helps in testing by providing a way to create mock objects, which can be used to simulate the behavior of real objects. These mock objects can be customized to return specific values or perform certain actions, allowing developers to test different scenarios and edge cases. By using mock objects, developers can isolate the code being tested and focus on specific functionality without having to worry about external dependencies.

Mockito also provides a simple and intuitive API for creating and configuring mock objects, making it easy for developers to write unit tests. The framework allows developers to verify the behaviour of mock objects and ensure that the code being tested is working as expected.

Overall, Mockito is a powerful tool that helps developers write better unit tests by simplifying the process of creating mock objects and verifying their behaviour. By using Mockito, developers can save time and improve the quality of their code, leading to more reliable and maintainable applications.

How do you create a mock object in Mockito?

To create a mock object in Mockito, you can use the Mockito.mock() method and pass the class or interface that you want to mock as an argument. Here’s an example:

Let’s say you have a UserService interface that you want to mock:

public interface UserService {

    public User getUserById(long userId);

    public List<User> getAllUsers();

    public void saveUser(User user);

}

To create a mock object of the UserService interface, you can use the following code:

UserService mockUserService = Mockito.mock(UserService.class);

This will create a mock object of the UserService interface that you can use in your tests.

Once you have created the mock object, you can use Mockito.when() method to define the behavior of the mock object. For example, to define the behavior of the getUserById() method, you can use the following code:

User mockUser = new User(“John”, “Doe”);

Mockito.when(mockUserService.getUserById(1L)).thenReturn(mockUser);

This will define the behavior of the getUserById() method to return a mock user object when called with the argument 1L.

You can also use the Mockito.verify() method to verify that certain methods of the mock object were called during the test. For example, to verify that the saveUser() method was called with a specific user object, you can use the following code:

User userToSave = new User(“Jane”, “Doe”);

mockUserService.saveUser(userToSave);

Mockito.verify(mockUserService).saveUser(userToSave);

This will verify that the saveUser() method was called with the userToSave object as an argument.

Difference between Stub and Mock Unit testing?

In unit testing, both stubs and mocks are used to simulate the behavior of objects that a class depends on, but there is a subtle difference between the two.

A stub is an object that provides predetermined responses to method calls made during a test. The purpose of a stub is to simplify the test by providing fixed inputs and outputs to the code being tested. A stub does not perform any verification or assertion of the interactions between the code being tested and the object being stubbed.

A mock object, on the other hand, is an object that is pre-programmed to expect certain interactions with the code being tested. A mock object is more complex than a stub, as it not only provides predetermined responses but also verifies that the correct methods are being called with the correct arguments. A mock object can be used to ensure that a particular method or set of methods are being called correctly, with the expected arguments and in the expected order.

In summary, the key difference between a stub and a mock object is that a stub is a simple object that provides pre-determined responses, while a mock object is a more complex object that can be programmed to expect and verify specific interactions with the code being tested.

What is the difference between a spy object and a mock object in Mockito?

In Mockito, a spy object is a real object that is being spied on, while a mock object is a completely fake object that is created by Mockito.

When a real object is used as a spy, Mockito wraps the object and allows you to intercept and stub certain method calls, while still calling the real methods of the object for any un-stubbed method calls. A spy object can be useful when you want to test a specific method of a real object while still maintaining its original behavior for other methods.

In contrast, a mock object is a completely fake object that is created by Mockito and provides predetermined responses to method calls. Mock objects are useful when you want to test how an object interacts with other objects and ensure that the correct methods are called with the correct arguments.

To summarize, the key difference between a spy object and a mock object in Mockito is that a spy object is a real object that is being spied on, while a mock object is a completely fake object. A spy object allows you to intercept and stub certain method calls while still calling the real methods of the object for un-stubbed method calls, while a mock object provides predetermined responses to method calls and can be used to ensure that the correct methods are called with the correct arguments.

How do you verify a method call on a mock object in Mockito?

In Mockito, you can use Mockito.verify() method to verify that a method was called on a mock object during a test.

To verify that a specific method was called on a mock object, you can use the following syntax:

Mockito.verify(mockObject).methodName(argument);

Here, mockObject is the mock object that you want to verify, methodName is the name of the method that you want to verify, and argument is the argument that was passed to the method. If the method was called with multiple arguments, you can pass all the arguments to the verify() method.

For example, if you have a mock object of a UserService interface and you want to verify that the saveUser() method was called with a specific user object, you can use the following code:

UserService mockUserService = Mockito.mock(UserService.class);

User userToSave = new User(“John”, “Doe”);

mockUserService.saveUser(userToSave);

Mockito.verify(mockUserService).saveUser(userToSave);

This will verify that the saveUser() method was called with the userToSave object as an argument.

You can also use the Mockito.verifyNoMoreInteractions() method to ensure that there are no other method calls on the mock object after the one you have verified. This can be useful in ensuring that there are no unexpected interactions with the mock object.

Mockito.verifyNoMoreInteractions(mockObject);

Overall, Mockito.verify() method is a powerful tool in Mockito that allows you to verify that specific methods were called on mock objects during unit tests.

How is the testing of the ‘protected’ method done?

In general, it is not recommended to test protected methods directly as they are not part of the public interface of a class and are intended to be used by subclasses only. However, there may be cases where you need to test a protected method, such as when the method contains complex logic that cannot be tested through the public interface of the class.

To test a protected method, you can create a test subclass of the class containing the protected method and call the method from within the test subclass. Since the test subclass is a subclass of the class being tested, it can access and invoke the protected method.

Here’s an example of how you can test a protected method using a test subclass:

public class MyClass {

    protected int myProtectedMethod(int a, int b) {

        return a + b;

    }

}

public class MyClassTest extends MyClass {

    @Test

    public void testMyProtectedMethod() {

        int result = myProtectedMethod(2, 3);

        assertEquals(5, result);

    }

}

In this example, the MyClassTest class extends MyClass, which allows it to access and invoke the protected myProtectedMethod() method. The test method testMyProtectedMethod() calls the myProtectedMethod() method with two arguments and verifies that the result is as expected.

It’s important to note that testing protected methods directly can be a sign of a design issue in your code. If you find yourself needing to test protected methods frequently, it may be worth re-evaluating the design of your class hierarchy and public interface to see if there is a better way to achieve your goals.

What is the purpose of the @Mock annotation in Mockito?

The @Mock annotation in Mockito is used to create a mock object for a class or interface in a test class. It is a shorthand way of creating mock objects without having to explicitly call the Mockito.mock() method.

When the @Mock annotation is used on a field in a test class, Mockito will automatically create a mock object of the type of that field and inject it into the test class. This allows the test class to use the mock object without having to create it explicitly.

Here’s an example of how to use the @Mock annotation in a test class:

public class MyTest {

    @Mock

    private MyService myService;

    @Test

    public void testSomething() {

        // Use the myService mock object in the test

        // …

    }

    @Before

    public void setUp() {

        MockitoAnnotations.openMocks(this);

    }

}

In this example, the MyTest class has a private field myService that is annotated with @Mock. Mockito will automatically create a mock object of the MyService class and inject it into the myService field when the test class is instantiated.

Note that in order for Mockito to create and inject the mock objects, you need to call the MockitoAnnotations.openMocks() method in the setUp() method of your test class. This initializes the mock objects and injects them into the annotated fields.

Overall, the @Mock annotation in Mockito makes it easier to create and use mock objects in your tests by automatically creating the mock objects and injecting them into your test class.

Can you explain the difference between @Mock and @InjectMocks annotations in Mockito?

The @Mock annotation is used to create mock objects of a class or interface in a test class. When a field is annotated with @Mock, Mockito creates a mock object of the type of the field and injects it into the field in the test class.

On the other hand, the @InjectMocks annotation is used to inject the mock objects created using @Mock into an instance of the class under test. This allows you to use the mock objects in your test methods without having to manually inject them.

Here’s an example to illustrate the difference:

public class MyTest {

    @Mock

    private MyService myService;

    @InjectMocks

    private MyClass myClass;

    @Test

    public void testSomething() {

        // Use the myService mock object in the test

        // Call methods on myClass, which will use the myService mock object

        // …

    }

    @Before

    public void setUp() {

        MockitoAnnotations.openMocks(this);

    }

}

In this example, the MyTest class has two fields annotated with @Mock and @InjectMocks. The myService field is annotated with @Mock, which creates a mock object of the MyService class. The myClass field is annotated with @InjectMocks, which injects the myService mock object into an instance of the MyClass class.

This allows you to use the myService mock object in your test methods by calling methods on the myClass instance, which will use the injected mock object.

Overall, the @Mock and @InjectMocks annotations serve different purposes in Mockito. The @Mock annotation is used to create mock objects of a class or interface in a test class, while the @InjectMocks annotation is used to inject those mock objects into an instance of the class under test.

Why can’t static methods be mocked using Mockito?

Mockito uses dynamic proxy classes to create mock objects, which only works with non-static methods. Static methods, on the other hand, are tied to the class itself and cannot be overridden or mocked using dynamic proxies.

Mockito relies on virtual method dispatch to redirect calls to mocked methods to the mock object instead of the real implementation. Virtual method dispatch only works with non-static methods, which are called on an instance of the class.

In addition, mocking static methods can have unwanted side effects and may not be a good testing practice. Static methods are global to the class and can affect other parts of the application, so mocking them could potentially cause unexpected behavior or break other tests.

Instead of mocking static methods, it is better to refactor the code to use instance methods or interfaces that can be mocked using Mockito. If refactoring is not possible, there are other testing frameworks, such as PowerMock, that allow mocking of static methods. However, it is important to use these tools with caution and only when absolutely necessary.

How do you configure a mock object to return a specific value in Mockito?

In Mockito, you can configure a mock object to return a specific value when a method is called on it using the when() and thenReturn() methods.

Here’s an example of how to configure a mock object to return a specific value:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Configure the mock object to return a specific value

when(myService.doSomething()).thenReturn(“value”);

// Call the method on the mock object

String result = myService.doSomething();

// Check that the mock object returned the expected value

assertEquals(“value”, result);

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then configure the mock object to return the string “value” when the doSomething() method is called on it using the when() and thenReturn() methods.

We then call the doSomething() method on the mock object and assign the result to a string variable. Finally, we check that the mock object returned the expected value using the assertEquals() method.

Overall, configuring a mock object to return a specific value is a simple process in Mockito using the when() and thenReturn() methods.

What is the role of ArgumentCaptor in Mockito?

The ArgumentCaptor class in Mockito is used to capture arguments passed to a method call on a mock object. It allows you to verify that the correct arguments were passed to a method call on a mock object, and to capture those arguments for further analysis or assertions.

Here’s an example of how to use ArgumentCaptor in Mockito:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Call the method on the mock object with some arguments

myService.doSomething(“arg1”, “arg2”);

// Create an ArgumentCaptor for the arguments of the doSomething() method

ArgumentCaptor<String> arg1Captor = ArgumentCaptor.forClass(String.class);

ArgumentCaptor<String> arg2Captor = ArgumentCaptor.forClass(String.class);

// Verify that the doSomething() method was called with the correct arguments

verify(myService).doSomething(arg1Captor.capture(), arg2Captor.capture());

assertEquals(“arg1”, arg1Captor.getValue());

assertEquals(“arg2”, arg2Captor.getValue());

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then call the doSomething() method on the mock object with two string arguments.

We then create two ArgumentCaptor objects, one for each argument of the doSomething() method, using the ArgumentCaptor.forClass() method. We pass the class of the argument to the method to indicate the type of argument we want to capture.

We then use the verify() method to verify that the doSomething() method was called on the mock object with the correct arguments. We pass the ArgumentCaptor objects to the method to capture the values of the arguments passed to the method.

Finally, we use the getValue() method of the ArgumentCaptor objects to get the captured values of the arguments, and we use the assertEquals() method to assert that the captured values are equal to the expected values.

Overall, the ArgumentCaptor class in Mockito is a useful tool for capturing arguments passed to a method call on a mock object and verifying that the correct arguments were passed.

Can you explain the concept of mocking void methods in Mockito?

In Mockito, mocking void methods involves verifying that a method that doesn’t return a value (i.e., a void method) was called on a mock object with specific arguments, without actually executing the method. This can be useful when testing methods that have side effects, such as writing to a database or sending a message to a queue.

Here’s an example of how to mock a void method in Mockito:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Call the method on the mock object with some arguments

myService.doSomethingVoid(“arg1”, “arg2”);

// Verify that the doSomethingVoid() method was called with the correct arguments

verify(myService).doSomethingVoid(“arg1”, “arg2”);

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then call the doSomethingVoid() method on the mock object with two string arguments.

We then use the verify() method to verify that the doSomethingVoid() method was called on the mock object with the correct arguments. We pass the expected arguments to the verify() method as parameters.

Note that because the doSomethingVoid() method doesn’t return a value, we don’t need to use the when() and thenReturn() methods to specify a return value.

If the void method has side effects that you need to test, you can use Mockito’s Mockito.verify() method to check that the side effects have occurred. For example, if the doSomethingVoid() method writes to a database, you can use the verify() method to check that the database was updated with the expected data.

Overall, mocking void methods in Mockito involves verifying that the method was called on a mock object with the expected arguments, without actually executing the method. This can be useful when testing methods with side effects.

What is the difference between doReturn() and when() in Mockito?

In Mockito, doReturn() and when() are both methods used for stubbing or mocking methods on a mock object, but they have slightly different use cases.

when() is used to stub a method call on a mock object and specify the return value of that method call. Here’s an example:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Stub the doSomething() method to return “result”

when(myService.doSomething()).thenReturn(“result”);

// Call the method on the mock object

String result = myService.doSomething();

// Assert that the result is “result”

assertEquals(“result”, result);

In this example, we create a mock object of the MyService class using Mockito.mock() method. We then use the when() method to stub the doSomething() method and specify that it should return the string “result” when called.

We then call the doSomething() method on the mock object, and the mock object returns the stubbed value of “result”. We use the assertEquals() method to assert that the returned value is equal to “result”.

On the other hand, doReturn() is used to stub a method call on a mock object and specify an action to be taken when the method is called. Here’s an example:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Stub the doSomething() method to print “hello” when called

doReturn(null).when(myService).doSomething();

// Call the method on the mock object

myService.doSomething();

// Verify that the doSomething() method was called

verify(myService).doSomething();

In this example, we create a mock object of the MyService class using Mockito.mock() method. We then use the doReturn() method to stub the doSomething() method and specify that it should print the string “hello” when called.

We then call the doSomething() method on the mock object, and the mock object prints “hello”. We use the verify() method to verify that the doSomething() method was called on the mock object.

Overall, the difference between doReturn() and when() in Mockito is that when() is used to stub a method call and specify the return value, while doReturn() is used to stub a method call and specify an action to be taken. Use when() when you want to specify the return value of a method call, and use doReturn() when you want to specify an action to be taken.

Difference between doReturn and thenReturn.

In Mockito, doReturn() and thenReturn() are both methods used for stubbing or mocking methods on a mock object. The main difference between them is in the types of methods they can be used with.

thenReturn() is used for stubbing a normal method call that returns a value. Here’s an example:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Stub the getValue() method to return 42

when(myService.getValue()).thenReturn(42);

// Call the method on the mock object

int result = myService.getValue();

// Assert that the result is 42

assertEquals(42, result);

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then use the thenReturn() method to stub the getValue() method and specify that it should return the value 42 when called.

We then call the getValue() method on the mock object, and the mock object returns the stubbed value of 42. We use the assertEquals() method to assert that the returned value is equal to 42.

On the other hand, doReturn() is used for stubbing a void method or a method that returns void. Here’s an example:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Stub the setValue() method to do nothing

doReturn(null).when(myService).setValue(42);

// Call the method on the mock object

myService.setValue(42);

// Verify that the setValue() method was called

verify(myService).setValue(42);

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then use the doReturn() method to stub the setValue() method and specify that it should do nothing when called with the argument 42.

We then call the setValue() method on the mock object with the argument 42, and the mock object doesn’t do anything. We use the verify() method to verify that the setValue() method was called on the mock object with argument 42.

Overall, the main difference between doReturn() and thenReturn() in Mockito is that thenReturn() is used for stubbing a method that returns a value, while doReturn() is used for stubbing a void method or a method that returns void. Use thenReturn() when you want to specify the return value of a method call, and use doReturn() when you want to specify that the method should do nothing or an alternative action when called.

How do you verify the order of method calls on a mock object in Mockito?

In Mockito, you can use the InOrder object to verify the order of method calls on a mock object. Here’s an example:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Call the methods on the mock object

myService.method1();

myService.method2();

myService.method3();

// Verify the order of method calls

InOrder inOrder = Mockito.inOrder(myService);

inOrder.verify(myService).method1();

inOrder.verify(myService).method2();

inOrder.verify(myService).method3();

 In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then call the method1(), method2(), and method3() methods on the mock object in a specific order.

We then create an InOrder object using Mockito.inOrder() method and pass in the mock object. We use the verify() method on the InOrder object to verify the order of method calls on the mock object. We specify the expected order of method calls by calling verify() on the mock object for each method call, in the order we expect them to be called.

If the order of method calls on the mock object doesn’t match the expected order, the test will fail.

Note that the InOrder object is only used for verifying the order of method calls on a single mock object. If you need to verify the order of method calls across multiple mock objects, you can create multiple InOrder objects, one for each mock object.

What is the purpose of the @Captor annotation in Mockito?

The @Captor annotation in Mockito is used to create an argument captor, which is a way to capture and inspect the arguments passed to a method during a test.

Here’s an example of how to use the @Captor annotation:

@Captor

private ArgumentCaptor<String> captor;

@Test

public void testMethod() {

  // Create a mock object

  MyService myService = Mockito.mock(MyService.class);

  // Call the method on the mock object

  myService.method(“argument”);

  // Verify that the method was called with the expected argument

  Mockito.verify(myService).method(captor.capture());

  assertEquals(“argument”, captor.getValue());

}

In this example, we use the @Captor annotation to create an ArgumentCaptor object that captures String arguments. We then create a mock object of the MyService class and call the method() method on it with the argument “argument”.

We use the verify() method on the mock object to verify that the method() method was called with the expected argument. We pass the captor object to the capture() method of Mockito.verify() to capture the argument passed to the method() method.

Finally, we use the getValue() method of the captor object to retrieve the captured argument and assert that it matches the expected value.

Using the @Captor annotation can make it easier to create argument captors and can help make tests more readable by separating the creation of the argument captor from the test logic.

Can you explain the concept of stubbing in Mockito?

In Mockito, stubbing refers to the process of specifying the behavior of a mock object when a particular method is called. When you stub a mock object, you are essentially telling Mockito what value or behavior it should return when a specific method is called.

Here’s an example of how to stub a method in Mockito:

// Create a mock object

MyService myService = Mockito.mock(MyService.class);

// Stub the behavior of the method

Mockito.when(myService.method()).thenReturn(“result”);

// Call the method on the mock object

String result = myService.method();

// Assert that the method returned the expected value

assertEquals(“result”, result);

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then use the Mockito.when() method to stub the behavior of the method() method on the mock object. We specify that when the method() method is called, it should return the string “result”.

We then call the method() method on the mock object and assign the return value to a variable. Finally, we use the assertEquals() method to assert that the value of the variable is equal to the expected value, which is “result” in this case.

Stubbing is a powerful feature of Mockito because it allows you to create mock objects that behave in a specific way, which can be useful for testing complex code that relies on external dependencies. By controlling the behavior of the mock object, you can isolate the code being tested and make the tests more reliable and repeatable.

What is the role of InOrder in Mockito?

The InOrder class in Mockito is used to verify that method calls on a mock object occur in a specific order. Sometimes it is necessary to verify that method calls on a mock object are made in a particular sequence, especially if the method calls have side effects that depend on the order of execution.

Here’s an example of how to use InOrder in Mockito:

// Create mock objects

MyService myService = Mockito.mock(MyService.class);

MyDao myDao = Mockito.mock(MyDao.class);

// Call methods on mock objects

myDao.save(“data”);

myService.process(“data”);

// Create an InOrder object

InOrder inOrder = Mockito.inOrder(myDao, myService);

// Verify that the methods were called in the correct order

inOrder.verify(myDao).save(“data”);

inOrder.verify(myService).process(“data”);

In this example, we create two mock objects of the MyService and MyDao classes using the Mockito.mock() method. We then call the save() method on the myDao mock object and the process() method on the myService mock object, in that order.

We create an InOrder object using the Mockito.inOrder() method and pass in the mock objects in the order that we expect the method calls to occur. We then use the verify() method of the InOrder object to verify that the save() method was called on the myDao mock object with the argument “data”, followed by the process() method on the myService mock object with the argument “data”.

If the method calls are not made in the expected order, the test will fail and the test output will indicate which method calls were out of order.

Using InOrder in Mockito can help make tests more reliable and ensure that method calls on mock objects are made in the correct order, which can be important for testing code that relies on specific sequences of method calls.

How do you handle exceptions in Mockito?

In Mockito, you can simulate exceptions by using Mockito.doThrow() method. This method allows you to specify an exception that should be thrown when a specific method on a mock object is called. Here’s an example:

MyService myService = Mockito.mock(MyService.class);

Mockito.doThrow(new RuntimeException()).when(myService).method();

try {

    myService.method();

    fail(“Expected RuntimeException was not thrown”);

} catch (RuntimeException ex) {

    // The exception was thrown as expected

}

In this example, we create a mock object of the MyService class using the Mockito.mock() method. We then use the Mockito.doThrow() method to specify that when the method() method on the mock object is called, it should throw a RuntimeException.

We then use a try-catch block to call the method() method on the mock object. Since we have specified that the method should throw an exception, we expect a RuntimeException to be thrown. If the exception is not thrown, the fail() method is called to indicate that the test failed.

By using Mockito.doThrow() to simulate exceptions, you can test how your code handles exceptions in various scenarios. This can help you identify and fix bugs in your code before they cause problems in production.

 What is the difference between Mockito.mock() and Mockito.spy() methods?

The Mockito.mock() and Mockito.spy() methods are both used in Mockito to create mock objects, but they behave differently.

The Mockito.mock() method creates a new mock object that is not associated with an actual instance of the class being mocked. When you call a method on a mock object created with Mockito.mock(), Mockito will return a default value for the method’s return type (e.g. null for object types, 0 for integers, etc.) unless you have configured it to do otherwise using the various mocking methods available in Mockito.

On the other hand, the Mockito.spy() method creates a spy object that wraps an actual instance of the class being spied on. When you call a method on a spy object created with Mockito.spy(), the method’s behavior will be the same as it would be on the actual instance of the class being spied on, unless you have explicitly overridden the method’s behavior using the various mocking methods available in Mockito.

In summary, Mockito.mock() creates a new mock object that does not have any behavior by default, while Mockito.spy() creates a spy object that delegates to the real implementation by default and can be stubbed or verified like a mock object.

Can you explain the concept of mocking final classes and methods in Mockito?

Mocking final classes and methods in Mockito can be challenging, as Mockito uses dynamic proxies and bytecode manipulation under the hood, and these techniques do not work with final classes and methods.

However, Mockito provides an experimental feature called mockito-inline, which allows you to mock final classes and methods using a different mechanism. To use this feature, you need to add the mockito-inline dependency to your project:

<dependency>

    <groupId>org.mockito</groupId>

    <artifactId>mockito-inline</artifactId>

    <version>3.6.0</version>

    <scope>test</scope>

</dependency>

Once you have added this dependency, you can use the @MockitoSettings annotation to enable the mockito-inline engine and allow Mockito to mock final classes and methods:

@ExtendWith(MockitoExtension.class)

@MockitoSettings(inlineMocks = true)

class MyTest {

    // …

}

Once you have enabled mockito-inline, you can use Mockito’s standard mocking syntax to create mocks of final classes and methods:final class MyFinalClass {

    final String myFinalMethod() {

        return “hello”;

    }

}

@Test

void testFinalClass() {

    MyFinalClass mock = Mockito.mock(MyFinalClass.class);

    Mockito.when(mock.myFinalMethod()).thenReturn(“world”);

    assertEquals(“world”, mock.myFinalMethod());

}

Note that the mockito-inline feature is still experimental, and its behavior may change in future versions of Mockito. Additionally, some limitations still apply, such as not being able to mock private or static final methods.

How do you verify a method call with specific arguments on a mock object in Mockito?

To verify that a specific method on a mock object is called with specific arguments in Mockito, you can use the verify() method with an argument matcher.

Here’s an example:

// Create a mock object of the dependency

MyDependency mockDependency = Mockito.mock(MyDependency.class);

// Call the method that uses the dependency

MyService myService = new MyService(mockDependency);

myService.doSomething(“foo”);

// Verify that the method on the mock object was called with the correct arguments

Mockito.verify(mockDependency).someMethod(Mockito.eq(“foo”));

In this example, we create a mock object of the MyDependency class using the Mockito.mock() method. We then create an instance of the MyService class, passing in the mock object as a dependency. We call the doSomething() method on the service, passing in the argument “foo”. Finally, we use the Mockito.verify() method to verify that the someMethod() method on the mock object was called with the argument “foo”, using the eq() matcher to match the argument.

You can also use other argument matchers, such as any(), isNull(), notNull(), startsWith(), endsWith(), etc. to match the arguments passed to the method on the mock object.

Note that if the method takes multiple arguments, you need to use an argument matcher for each argument in the verify() method. For example, if the method takes two arguments, you could use the following syntax:

Mockito.verify(mockDependency).someMethod(Mockito.eq(“foo”), Mockito.anyInt());

This would verify that the someMethod() method on the mock object was called with the argument “foo” and any integer as the second argument.

What is the purpose of the @MockBean annotation in Spring Boot?

The @MockBean annotation is a feature of Spring Boot’s testing framework that allows you to create mock objects of external dependencies that your application relies on. This is useful for testing the behavior of your application in isolation, without actually relying on the real implementation of these external dependencies.

When you use the @MockBean annotation, Spring Boot will create a mock object of the specified type and inject it into the Spring ApplicationContext, replacing any existing bean of that type. This means that when your application runs, it will use the mock object instead of the real implementation of the dependency.

Here’s an example of how you could use the @MockBean annotation to mock a dependency in a Spring Boot test:

@RunWith(SpringRunner.class)

@SpringBootTest

public class MyServiceTest {

    @MockBean

    private MyDependency myDependency;

    @Autowired

    private MyService myService;

    @Test

    public void testDoSomething() {

        // Set up the mock object to return a specific value

        Mockito.when(myDependency.someMethod()).thenReturn(“foo”);

        // Call the method under test

        String result = myService.doSomething();

        // Verify that the mock object was called with the correct arguments

        Mockito.verify(myDependency).someMethod();

        // Verify the result

        Assert.assertEquals(“Expected result”, result);

    }

}

In this example, we use the @MockBean annotation to create a mock object of the MyDependency class. We then inject this mock object into our MyService class using the @Autowired annotation. We can then use the Mockito.when() and Mockito.verify() methods to set up and verify the behavior of the mock object. Note that we also use the @SpringBootTest and @RunWith(SpringRunner.class) annotations to load the Spring ApplicationContext and run the test in a Spring context.

By using the @MockBean annotation, we can test the behavior of our MyService class in isolation, without actually relying on the real implementation of MyDependency.

Can you explain the difference between @MockBean and @Autowired annotations in Spring Boot?

The @Autowired annotation is used to inject an instance of a bean that is managed by the Spring ApplicationContext into a class or a field. This allows you to use the bean in your code, and it will be automatically created and managed by Spring. The @Autowired annotation can be used to inject any bean, whether it is a mock or a real implementation.

On the other hand, the @MockBean annotation is used to create a mock object of an external dependency that your application relies on. This mock object is then injected into the Spring ApplicationContext in place of the real implementation of the dependency. The @MockBean annotation can only be used to create mock objects, and it is typically used in test classes to isolate the behavior of your application.

Here’s an example to illustrate the difference:

@Service

public class MyService {

    @Autowired

    private MyDependency myDependency;

    public String doSomething() {

        // Use the MyDependency bean

        return myDependency.someMethod();

    }

}

@RunWith(SpringRunner.class)

@SpringBootTest

public class MyServiceTest {

    @MockBean

    private MyDependency myMockDependency;

    @Autowired

    private MyService myService;

    @Test

    public void testDoSomething() {

        // Set up the mock object to return a specific value

        Mockito.when(myMockDependency.someMethod()).thenReturn(“foo”);

        // Call the method under test

        String result = myService.doSomething();

        // Verify that the mock object was called with the correct arguments

        Mockito.verify(myMockDependency).someMethod();

In this example, we have a MyService class that has a dependency on a MyDependency bean, which is injected using the @Autowired annotation. In the MyServiceTest class, we use the @MockBean annotation to create a mock object of the MyDependency class, and then use the Mockito.when() and Mockito.verify() methods to set up and verify the behavior of the mock object.

So, to summarize, @Autowired is used to inject real beans managed by Spring, while @MockBean is used to create mock objects of external dependencies.

What is the role of @InjectMocks annotation in Mockito?

The @InjectMocks annotation in Mockito is used to automatically inject mock objects into the fields of a class that is being tested. This allows you to easily create and manage the dependencies of the class under test.

When you use the @InjectMocks annotation, Mockito will attempt to find instances of all the mock objects that have been created using the @Mock or @Spy annotations, and inject them into the fields of the class being tested. Mockito will use the type of the field to determine which mock object to inject.

Here’s an example to illustrate how @InjectMocks works:

public class MyService {

    private MyDependency myDependency;

    public String doSomething() {

        // Use the MyDependency bean

        return myDependency.someMethod();

    }

    // Other methods and dependencies…

}

@RunWith(MockitoJUnitRunner.class)

public class MyServiceTest {

    @Mock

    private MyDependency myMockDependency;

    @InjectMocks

    private MyService myService;

    @Test

    public void testDoSomething() {

        // Set up the mock object to return a specific value

        Mockito.when(myMockDependency.someMethod()).thenReturn(“foo”);

        // Call the method under test

        String result = myService.doSomething();

        // Verify that the mock object was called with the correct arguments

        Mockito.verify(myMockDependency).someMethod();

        // Verify the result

        Assert.assertEquals(“Expected result”, result);

    }

}

In this example, we have a MyService class that has a dependency on a MyDependency bean. In the MyServiceTest class, we use the @Mock annotation to create a mock object of the MyDependency class, and use the @InjectMocks annotation to inject the mock object into the myDependency field of the MyService class.

When we run the test, Mockito will automatically create the mock object and inject it into the myDependency field of the MyService object. This allows us to easily test the behavior of the MyService class, without having to manually create and manage its dependencies.

So, to summarize, the @InjectMocks annotation is used to automatically inject mock objects into the fields of a class that is being tested, based on their type.

Can you explain the difference between static and non-static methods in Mockito?

In Mockito, there is no difference between mocking static and non-static methods – both can be mocked using the same set of Mockito APIs. However, there are some differences in the way static and non-static methods are handled at the JVM level.

In Java, static methods are associated with the class, while non-static methods are associated with instances of the class. This means that when you call a static method, you don’t need an instance of the class, while when you call a non-static method, you need an instance of the class.

When you mock a static method using Mockito, Mockito creates a proxy class that extends the original class and overrides the static method you want to mock. This proxy class is used instead of the original class when the mocked static method is called.

When you mock a non-static method using Mockito, Mockito creates a proxy object that implements the class or interface of the object you want to mock. This proxy object is used instead of the original object when the mocked non-static method is called.

In terms of usage, mocking static methods is generally discouraged, as it can make your tests brittle and harder to maintain. This is because static methods are typically used for utility functions or for accessing the global states, which can lead to unexpected side effects and make it difficult to isolate the behavior you’re testing.

On the other hand, mocking non-static methods is a common practice in unit testing, as it allows you to isolate the behavior of individual objects and test their interactions with other objects. By mocking non-static methods, you can control the behavior of the object being tested and verify that it interacts correctly with other objects in your system.

What is the purpose of the reset () method in Mockito?

In Mockito, the reset() method is used to reset a mock object’s state to its initial configuration. This means that all stubbing and interactions that have been performed on the mock object are removed, and the mock object is returned to a “clean slate” state.

The reset() method can be useful in situations where you want to reuse a mock object in multiple test cases, or if you want to ensure that the mock object is in a consistent state before each test case is run. By resetting the mock object between tests, you can ensure that each test starts with the same initial conditions, which can make it easier to write and maintain your test cases.

Here’s an example of how to use the reset() method in Mockito:

// Create a mock object

MyObject mockObject = mock(MyObject.class);

// Stub a method on the mock object

when(mockObject.myMethod()).thenReturn(“hello”);

// Use the mock object in a test

assertEquals(“hello”, mockObject.myMethod());

// Reset the mock object

reset(mockObject);

// Use the mock object in another test

assertNull(mockObject.myMethod());

In this example, we create a mock object and stub a method on it. We then use the mock object in a test and verify that the stubbed method returns the expected value. We then reset the mock object using the reset() method and use it in another test, verifying that the stubbed method now returns null, as we have removed the stubbing.

How do you verify the number of method calls on a mock object in Mockito?

In Mockito, you can verify the number of method calls on a mock object using the verify() method. The verify() method allows you to check that a particular method on the mock object was called a specific number of times.

Here’s an example:

// Create a mock object

List<String> mockList = mock(List.class);

// Call a method on the mock object

mockList.add(“foo”);

// Verify that the method was called exactly once

verify(mockList, times(1)).add(“foo”);

In this example, we create a mock object of the List class and call the add() method on it once. We then use the verify() method to check that the add() method was called exactly once with the argument “foo”.

The times() method is used to specify the number of times the method should have been called. In this case, we pass 1 to times() to indicate that the method should have been called exactly once.

You can also use other methods, such as atLeastOnce(), atMost(), never(), and others to specify the expected number of method calls.

For example:

// Verify that the method was called at least once

verify(mockList, atLeastOnce()).add(“foo”);

// Verify that the method was called at most twice

verify(mockList, atMost(2)).add(“foo”);

// Verify that the method was never called with “bar”

verify(mockList, never()).add(“bar”);

These methods can be useful for verifying that your code is calling methods on a mock object as expected, which can help ensure that your tests are properly testing your code’s behavior.

Can you explain the concept of mocking private methods in Mockito?

Mockito does not support mocking of private methods because the Mockito framework relies on the Java Reflection API to create mocks, and the Reflection API cannot access private methods directly.

However, it is possible to mock private methods in Mockito by using a technique called “partial mocking” or “spy objects”. This technique involves creating a “partial mock” or a “spy” of an object, which allows you to mock specific methods of that object while still calling the real implementation of other methods.

Here’s an example of how to use partial mocking to mock a private method in Mockito:

public class MyClass {

  private String privateMethod() {

    return “private method”;

  }

  public String publicMethod() {

    return “public method: ” + privateMethod();

  }

}

In this example, MyClass has a private method called privateMethod() and a public method called publicMethod() that calls the private method. We want to test the publicMethod() method, but we don’t want to call the private method directly because it might have side effects that we don’t want to trigger during our test.

To mock the private method, we can create a spy object of MyClass and use the doReturn() method to mock the behavior of the private method:

@Test

public void testPublicMethod() throws Exception {

  MyClass spyObject = spy(new MyClass());

  doReturn(“mocked private method”).when(spyObject, “privateMethod”);

  String result = spyObject.publicMethod();

  assertEquals(“public method: mocked private method”, result);

}

In this example, we create a spy object of MyClass and use the doReturn() method to mock the behavior of the private method. We pass the spy object and the name of the private method to doReturn() to indicate which method we want to mock. We then call the publicMethod() method on the spy object, which will call the mocked version of privateMethod() instead of the real implementation.

By using partial mocking, we can mock the behavior of private methods in Mockito and test our code in isolation without triggering any unwanted side effects. However, it’s worth noting that this technique can make our tests more brittle because we’re testing the implementation details of our code, rather than its public API.

Can you list out some Mockito Annotations?

Here are some commonly used Mockito annotations:

  1. @Mock: This annotation is used to create a mock object of a class or interface. The mock object can be used to stub methods and verify interactions.
  2. @Spy: This annotation is used to create a spy object of a class. A spy object is a partial mock that allows you to call the real implementation of some methods while mocking others.
  3. @Captor: This annotation is used to create an ArgumentCaptor, which allows you to capture the arguments passed to a method call on a mock object.
  4. @InjectMocks: This annotation is used to inject mock objects into a class that you want to test. The mock objects are automatically created and injected into the class under test.
  5. @RunWith(MockitoJUnitRunner.class): This annotation is used to run JUnit tests with Mockito. It initializes the mock objects and verifies the interactions after the test has completed.
  6. @Before, @After: These annotations are used to specify methods that should be run before or after each test method. For example, you can use the @Before annotation to create the mock objects before each test, and the @After annotation to reset the mock objects after each test.

These annotations are just a few of the annotations available in Mockito. By using these annotations, you can write clean and concise tests that are easy to read and maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *