Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing a value passed to a static method

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?

like image 883
Willy willy Avatar asked May 12 '26 04:05

Willy willy


2 Answers

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

  • you may not be testing exactly the same bytecode you use in production (say hello to Heisenbugs) and
  • this can screw with other tools, e.g. JaCoCo

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.

like image 57
Turing85 Avatar answered May 14 '26 17:05

Turing85


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.

like image 23
Anatolii Avatar answered May 14 '26 18:05

Anatolii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!