How to mock a static method without powermock

Is there a way we can make fun of the static util method during testing in JUnit?

I know that Powermock can make fun of static calls, but I do not want to use Powermock.

Are there any alternatives?

+19
source share
3 answers

(I assume you can use Mockito, though) Nothing special comes to my mind, but I tend to use the following strategy when it comes to situations like this:

1) In the tested class, replace the direct static call with a call to the package level method, which includes the static call itself:

public class ToBeTested{ public void myMethodToTest(){ ... String s = makeStaticWrappedCall(); ... } String makeStaticWrappedCall(){ return Util.staticMethodCall(); } } 

2) Spy on the tested class during testing and simulate the method of the package level:

 public class ToBeTestedTest{ @Spy ToBeTested tbTestedSpy = new ToBeTested(); @Before public void init(){ MockitoAnnotations.initMocks(this); } @Test public void myMethodToTestTest() throws Exception{ // Arrange doReturn("Expected String").when(tbTestedSpy).makeStaticWrappedCall(); // Act tbTestedSpy.myMethodToTest(); } } 

Here is an article I wrote about espionage that has a similar case if you need more information: sourceartists.com/mockito-spying

+14
source

When you have static code that gives you problems in your unit tests; so that you feel that you need to "mock", you have these options:

  • You go to PowerMock (ito). It works great.
  • You are accessing JMockit. Works well too.
  • If you are testing code that you yourself wrote, you may need to step back and ask yourself: "Why did I write code that is now difficult for me to find unit test?"

In other words: if you want to use a fake framework, you must use one of the above. On the one hand, this is absolutely true. static is one part of the Java language; so why not use a framework that allows you to handle this?

But, of course, you still have a static call in your production code. Leading to a tight bond and preventing polymorphism.

So: if you can get rid of the static call (even when using the workaround suggested in another answer), all the better. If not: Mokito cannot help; you will need the magic of manipulating byte code or. JVM agents.

+4
source

I was very lucky when I did something similar to what Maciej suggested in his answer above. In Java8, I like to wrap these static methods with functional interfaces to make them easier to implement or simulate. For instance:

 public class MyClass { private MyStaticWrapper staticWrapper; public MyClass(final MyStaticWrapper staticWrapper) { this.staticWrapper = staticWrapper; } public void main() { ... staticWrapper.doSomething(); ... } } public interface MyStaticWrapper { default void doSomething() { Util.annoyingUntestableStaticFunction(); } } 
0
source

Source: https://habr.com/ru/post/1269593/


All Articles