Mocking a Function in the Same Class You Are Testing in Java
Unit testing is an essential aspect of Test-Driven Development (TDD) that ensures the quality of your implementation. In Java, JUnit is often used to perform unit testing, and sometimes you’ll need to mock classes or methods. Mocking allows you to define the return value of a method without actually executing its steps, which is useful when testing methods that have external communication, like database calls or REST calls. In this article, we’ll discuss how to mock a method in the same class you’re testing using Mockito.
Consider the following Vehicle class with external communication:
public class Vehicle {
// Class fields and methods...
public boolean checkEngine(String engineType) {
// This method returns a value by checking a database
}
public boolean isOperable() {
// This method calls checkEngine(String engineType)
}
}
In this example, we want to test the isOperable()
method without executing the checkEngine(String engineType)
method and communicating with the database.
Step 1: Create a VehicleTest class
First, create a VehicleTest class, which will contain the unit tests for the Vehicle class.
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class VehicleTest {
// Test methods...
}
Step 2: Use Mockito.spy() to mock the Vehicle class
Instead of using mock(class)
, you need to use Mockito.spy()
to mock the same class you're testing.
@Test
public void operableTest() {
Vehicle vehicle = new Vehicle("engineType");
Vehicle vehicle1 = Mockito.spy(vehicle);
// ...
}
Step 3: Mock the checkEngine(String engineType) method
Now that you have a spy object, you can mock the checkEngine(String engineType)
method using the doReturn()
method in Mockito.
@Test
public void operableTest() {
Vehicle vehicle = new Vehicle("engineType");
Vehicle vehicle1 = Mockito.spy(vehicle);
Mockito.doReturn(true).when(vehicle1).checkEngine("engineType");
Assert.assertEquals(true, vehicle1.isOperable());
}
In this example, we’ve mocked the checkEngine(String engineType)
method of the Vehicle class to always return true
for the given engine type. This allows us to test the isOperable()
method without executing the actual checkEngine(String engineType)
method and interacting with the database.
Conclusion:
Using Mockito.spy(), you can effectively mock methods in the same class you’re testing, allowing you to isolate specific behaviors for testing purposes. This technique can help you create more efficient and reliable unit tests for your Java applications. Happy coding and testing!