Java mockito example interview questions

Nicholas 75 Published: 10/24/2024

Java mockito example interview questions

Here are some common Java Mockito interview questions and examples:

What is the purpose of Mockito?

Mockito is a mocking library that allows you to isolate dependencies and test units in isolation. It provides a way to create mock objects that mimic the behavior of real objects, making it easier to write unit tests.

Example:

// Real code

public class Service {

private final Repository repository;

public Service(Repository repository) {

this.repository = repository;

}

public void doSomething() {

repository.getData();

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Repository

Repository repositoryMock = Mockito.mock(Repository.class);

// Define the behavior of the mock

Mockito.when(repositoryMock.getData()).thenReturn("Mocked data");

// Create an instance of the Service with the mock

Service service = new Service(repositoryMock);

// Test the doSomething method

service.doSomething();

}

}

How do you create a spy in Mockito?

A spy is an object that acts as both a real and a fake object at the same time. It allows you to verify the interactions between two or more objects while also allowing you to use a fake implementation for one of those objects.

Example:

// Real code

public class Controller {

private final Service service;

public Controller(Service service) {

this.service = service;

}

public void doSomething() {

service.doSomething();

}

}

// Testing with Mockito

public class ControllerTest {

@Test

public void testDoSomething() {

// Create a spy for the Service

Service serviceSpy = Mockito.spy(new Service(new Repository()));

// Set up the expectations on the service

Mockito.when(serviceSpy.doSomething()).thenReturn("Mocked data");

// Create an instance of the Controller with the spy

Controller controller = new Controller(serviceSpy);

// Test the doSomething method

controller.doSomething();

}

}

How do you handle exceptions in Mockito?

You can use the doThrow() method to specify that a mock should throw an exception when its methods are called.

Example:

// Real code

public class Service {

public void doSomething() throws Exception {

// Code that might throw an exception

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Define the behavior of the mock

Mockito.doThrow(new Exception()).when(serviceMock).doSomething();

try {

// Test the doSomething method

serviceMock.doSomething();

} catch (Exception e) {

// Assert that the expected exception was thrown

assertEquals("Expected exception", e.getMessage());

}

}

}

How do you verify interactions in Mockito?

You can use the verify() and verifyNoInteractions() methods to verify that a mock has received certain interactions.

Example:

// Real code

public class Controller {

private final Service service;

public Controller(Service service) {

this.service = service;

}

public void doSomething() {

service.doSomething();

}

}

// Testing with Mockito

public class ControllerTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Set up the expectations on the service

Mockito.when(serviceMock.doSomething()).thenReturn("Mocked data");

// Create an instance of the Controller with the mock

Controller controller = new Controller(serviceMock);

// Test the doSomething method

controller.doSomething();

// Verify that the service was called

Mockito.verify(serviceMock).doSomething();

}

}

How do you use Mockito's thenAnswer() method?

The thenAnswer() method allows you to specify a custom answer for a mock object.

Example:

// Real code

public class Service {

public void doSomething() {

// Code that uses a database connection

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Define the behavior of the mock using thenAnswer()

Mockito.when(serviceMock.doSomething()).thenAnswer(new Answer() {

Object answer() {

return "Mocked data";

}

});

// Test the doSomething method

assertEquals("Mocked data", serviceMock.doSomething());

}

}

How do you use Mockito's argumentCaptor() method?

The argumentCaptor() method allows you to capture the arguments passed to a mock object.

Example:

// Real code

public class Service {

public void doSomething(String argument) {

// Code that uses the argument

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Define the behavior of the mock using thenArgumentCaptor()

ArgumentCaptor argumentCaptor = ArgumentCaptor.capture();

Mockito.when(serviceMock.doSomething(argumentCaptor.capture())).thenReturn("Mocked data");

// Test the doSomething method

serviceMock.doSomething("Test argument");

// Verify that the captured argument is correct

assertEquals("Test argument", argumentCaptor.getValue());

}

}

How do you use Mockito's doReturn() method?

The doReturn() method allows you to specify a custom return value for a mock object.

Example:

// Real code

public class Service {

public Object getData() {

// Code that returns data from a database

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testGetData() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Define the behavior of the mock using doReturn()

Object returnObject = new Object();

Mockito.doReturn(returnObject).when(serviceMock).getData();

// Test the getData method

assertEquals(returnObject, serviceMock.getData());

}

}

How do you use Mockito's thenThrow() method?

The thenThrow() method allows you to specify an exception that should be thrown when a mock object's methods are called.

Example:

// Real code

public class Service {

public void doSomething() throws Exception {

// Code that might throw an exception

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Define the behavior of the mock using thenThrow()

Mockito.thenThrow(new Exception()).when(serviceMock).doSomething();

try {

// Test the doSomething method

serviceMock.doSomething();

} catch (Exception e) {

// Assert that the expected exception was thrown

assertEquals("Expected exception", e.getMessage());

}

}

}

How do you use Mockito's verify() method with a timeout?

The verify() method allows you to specify a timeout for verifying interactions.

Example:

// Real code

public class Service {

public void doSomething() {

// Code that takes some time to complete

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Set up the expectations on the service

Mockito.when(serviceMock.doSomething()).thenReturn("Mocked data");

// Test the doSomething method

serviceMock.doSomething();

// Verify that the service was called with a timeout of 1 second

Mockito.verify(serviceMock, timeout(1000)).doSomething();

}

}

How do you use Mockito's times() method?

The times() method allows you to specify how many times a mock object should be called.

Example:

// Real code

public class Service {

public void doSomething() {

// Code that does something

}

}

// Testing with Mockito

public class ServiceTest {

@Test

public void testDoSomething() {

// Create a mock for the Service

Service serviceMock = Mockito.mock(Service.class);

// Set up the expectations on the service

Mockito.when(serviceMock.doSomething()).thenReturn("Mocked data");

// Test the doSomething method 3 times

for (int i = 0; i < 3; i++) {

serviceMock.doSomething();

}

// Verify that the service was called exactly 3 times

Mockito.verify(serviceMock, Mockito.times(3)).doSomething();

}

}

These are some common Java Mockito interview questions and examples. Remember to practice answering these types of questions so you feel more confident during your interviews!

What is Mockito used for in Java?

Mockito is a popular mocking library in Java that allows developers to create mock objects with specific behaviors for testing purposes. It provides a simple and intuitive API for creating mocks, stubs, and spies, making it easier to write unit tests for Java-based applications.

One of the primary uses of Mockito is to isolate dependencies between classes or methods under test. By mocking out external dependencies, developers can ensure that their code is being tested in isolation, without worrying about the behavior of external systems or services. This makes it easier to focus on the specific piece of code being tested and reduce the complexity of the test environment.

Mockito's power lies in its flexibility. Developers can create mocks with a wide range of behaviors, from simple returns to complex calculations. Mockito supports a variety of mocking techniques, including:

Stubbing: Mockito allows developers to define custom behavior for methods on mock objects. This enables testing specific scenarios and edge cases. Spies: Spies are similar to stubs but track method invocations and allow developers to verify that certain methods were called with specific arguments. Verifiable: Verifiable mocks record method invocations, making it possible to assert that certain methods were called a certain number of times.

Mockito's API is designed to be easy to use and understand, even for developers new to testing. The library provides a range of features, such as:

Annotated mock creation: Mockito supports creating mocks using Java annotations, making it easy to define the behavior of mock objects. Method chaining: Mockito allows developers to chain method calls together, enabling more concise and expressive tests. Extensive API documentation: The official Mockito documentation provides extensive examples, tutorials, and best practices for using the library.

Some common use cases for Mockito include:

Testing web services or APIs: By mocking out external dependencies, developers can test their code's interaction with APIs or services without relying on actual network connections. Isolating database interactions: Mockito enables developers to test code that interacts with databases without actually querying the database or modifying its state. Verifying business logic: Mockito helps developers test complex business logic and workflows by creating mock objects that mimic the behavior of external systems or services.

In summary, Mockito is a powerful tool in Java that simplifies the process of writing unit tests by allowing developers to create custom behaviors for mock objects. Its flexibility, ease of use, and extensive documentation make it an invaluable resource for any Java developer working with unit testing.