Creating a mock

In this post under Mockito, I will show with example how to create a mock of a class.

For our example I will use the “Calculator” class with below structure.

Calculator

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

As you can see, the above “Calculator” class has two methods “add” and “multiple”.

Now to create a mock of the “Calculator” class, I will use public static non-void method “mock” of Mockito class.

This “mock” method takes the “Class” object of the class to be mocked as an argument and returns a mock instance of the class.

So in our example, to create a mock of “Calculator” class, we need to have the below code snippet.

Calculator calculator = Mockito.mock(Calculator.class);

In this way we can create a mock of a class.

Below is the test class for your reference

Test class

package package1;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = Mockito.mock(Calculator.class);
assertNotNull(calculator);
}
}

Leave a comment