Using @Mock annotation

In my previous post under Mockito, I showed you with example how to manually create a mock.

In this post under Mockito, I will show with example how to tell Mockito to create a mock and assign the reference to a variable.

To tell Mockito framework to create a mock of a class and assign the reference to a variable we follow the below steps.
1) Annotate the test class with “@ExtendWith(MockitoExtension.class)”
2) We need to declare an instance field of the type we want to mock in the test class
3) annotate the field with “@Mock” annotation

Lets see an example, for our example I will create “Calculator” class with below structure

Calculator

package package2;
public class Calculator {
public int add(int x, int y) {
return x + y;
}
public int multiple(int x, int y) {
return x * y;
}
}

Below is the test class where I want a mock of “Calculator” class to be injected.

Test class

package package2;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ExtendWith(MockitoExtension.class)
public class CalculatorTest {
@Mock
private Calculator calculator;
@Test
public void testAdd() {
assertNotNull(calculator);
}
}

In the above code, at line 14, I declared a field “calculator” to type “Calculator” class and annotate it with “@Mock” annotation.

So when the test class is run, a mock of “Calculator” class is automatically created and assigned to the variable “calculator”.

In this way we can instruct Mockito to automatically create a mock and assign it to a variable.

Leave a comment