Example code:
class MyClass {
public void myMethod(Request request) {
Item item = getItem();
ItemUtilHelper.setCertainProperties(newProperty, item);
differentClass.staticMethod(item);
}
}
The ItemUtilHelper already has a unit test class to verify item gets properly updated.
How would I go about unit testing that differentClass.staticMethod gets called with an updated item parameter?
Let me start by saying that the static method in and of itself is a code smell. Miško Hevery summed up it quite nicely by saying:
The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation.
If you want to use Mockito only, your problem is not solvable:
What are the limitations of Mockito
Mockito 2.x specific limitations
...
Cannot mock static methods
...
(See Mockito FAQ)
You can use PowerMock to achieve your goal. But be warned: PowerMock operates on bytecode level. This means that
If you still want to proceed, then what you are looking for is a Spy. You can find a tutorial on PowerMock's wiki. While not directly related, the answers to this question give some additional examples on how to create a spy of a class. A throughout example can be found on Automation Rhapsody.
In addition to what @Turing85 said it's better to refactor static methods into public non-static ones. Then, an object possessing such methods can be passed into a method or constructor as a parameter and thus easily mocked or spied on. By doing so, you easily test your method logic and don't worry about object dependencies which functionality you don't want to test at the moment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With