Icon TP 149

Testing with Mockito

Problem

With its possibilities to mock classes, Mockito is a very powerful tool. But when the equals() methods of the objects to be checked do not exist or are faulty, Mockito reaches its limits with its verify() methods. Normally, the classes are simply fixed and that’s it. In the case of external classes, it’s not that simple. There are several possibilities: transferring them into their own classes, hiding them very well in a wrapper or switching straight to Kotlin.

Solution

A useful solution to completely test the code is to use ArgumentCapture. This makes it possible to capture the instances during verify() and check them later.

Example

1 FuelPortion expectedFuelPortion = FuelPortion.DYNAMIC;
2
3 Engine myMockEngine = mock(Engine.class); //Or with @Mock
4 Car myTestCar = new Car(myMockEngine);
5
6 myTestCar.startEngine();
7
8 ArgumentCaptor<EngineConfiguration> engineConfigurationCapture = ArgumentCaptor.forClass(EngineConfiguration.class); //Or with @Captor
9 verify(myMockEngine).start(engineConfigurationCapture.capture()); // capture() is the central call for ArgumentCapture
10
11 EngineConfiguration actuelEngineConfiguration = engineConfigurationCapture.getValue();
12 Assert.assertEquals(expectedFuelPortion, actuelEngineConfiguration.getFuelPortion());
TP 149 Visual

Further Aspects

---

Author: Alexander Pöhlmann / Software Engineer / Office Leipzig

Cookie Settings

This website uses cookies to personalize content and ads, provide social media features, and analyze website traffic. In addition, information about your use of the website is shared with social media, advertising, and analytics partners. These partners may merge the information with other data that you have provided to them or that they have collected from you using the services.

For more information, please refer to our privacy policy. There you can also change your cookie settings later on.

contact icon

Contact us now