How to mock static method without powermock

前端 未结 4 1677
野趣味
野趣味 2020-12-09 01:53

Is there any way we can mock the static util method while testing in JUnit?

I know Powermock can mock static calls, but I don\'t want to use Powermock.

Are

4条回答
  •  甜味超标
    2020-12-09 02:23

    When you have static code that gives you trouble in your unit tests; so that you feel you have to "mock it away", you have exactly these options:

    • You turn to PowerMock(ito). Works fine.
    • You turn to JMockit. Works fine, too.
    • If you are testing code you have written yourself, you might want to step back and ask yourself: "why did I write code that I now find hard to unit test?"

    In other words: if you want to use a mocking framework, you have to use one of those listed above. On the one side, that is absolutely fair. static is one part of the Java language; so why not use a framework that allows you to deal with it?

    But of course: you still have the static call in your production code then. Leading to tight coupling, and preventing polymorphism.

    So: if you can get rid of the static call (even when just using the workaround suggested in the other answer) - all the better. If not: Mockito can't help; you need the magic of byte code manipulation resp. JVM agents.

提交回复
热议问题