I need to mock a static method with junit5 (that's is very important) and mockito or easymock. I saw that powermock works only with junit 4. there exists any form to do it with junit5?
-
Does this answer your question? [Junit5 mock a static method](https://stackoverflow.com/questions/52830441/junit5-mock-a-static-method/63242611#answer-63242611) – angelcervera Aug 04 '20 at 08:41
-
Basically, [It is possible from version Mockito 3.4.0 without extensions](https://stackoverflow.com/questions/52830441/junit5-mock-a-static-method/63242611#answer-63242611) – angelcervera Aug 04 '20 at 08:47
2 Answers
Not from as far as I know. The easiest will be to shield it with a non-static method.
public class A {
void foo() {
Stuff s = MyClass.getStuff();
}
}
will become
public class A {
private final StuffProxy stuffProxy;
public A(StuffProxy stuffProxy) {
this.stuffProxy = stuffProxy;
}
public A() {
this(new StuffProxy());
}
void foo() {
Stuff s = stuffProxy.get();
}
}
public class StuffProxy {
public Stuff get() {
return MyClass.getStuff();
}
}
Then you mock StuffProxy
.

- 5,551
- 1
- 22
- 29
Mocking of static methods is not possible without PowerMock. And when you need PowerMock, it means that the code is not developed correctly, in the way it is testable. I am working on a project with Java 11, JUnit 5 and Mockito. PowerMock does not support this at all. And I doubt it will ever support it.
That being said: the only way to make it testable is to have the class-with-static-method injected into the class you need to test and then replace the implementation of the bean in the test-scope with a mock. When you inject it, you have a live object, so no need for a static method anymore.
It has benefits to change the code and use an injection framework (like Spring). I know there are situations you can't just do this. If you really can't change the implementation, just leave this for what it is and make a lot of unit tests to test the static method by itself with all kind of parameters. Just to make sure this class works as expected.

- 2,343
- 1
- 18
- 29