Reputation: 53
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?
Upvotes: 5
Views: 10160
Reputation: 2563
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.
Upvotes: 1
Reputation: 5731
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
.
Upvotes: 1