Reputation: 1139
I have a library I am trying to mock for testing... There is a Java 8 interface with a static method implementation like this:
public interface Router {
public static Router router(Object param) {
return new RouterImpl(param);
}
}
And I am trying to mock that returned value:
PowerMockito.mockStatic(Router.class);
PowerMockito.doReturn(mockRouter).when(Router.router(any()));
But when I run the tests through a debugger, the mock instance is not returned.
I've tried a number of different permutations of the static mocking, but I cannot get the static method to return my mock value. Any thoughts?
Upvotes: 3
Views: 3227
Reputation: 4643
You are doing it right, but we will have to wait when mocking static interface method is implemented/fixed in PowerMock. Watch this pull request: https://github.com/jayway/powermock/issues/510
Note: Good news is that issue in Javassist is already fixed:
https://github.com/jboss-javassist/javassist/pull/11
Upvotes: 4
Reputation: 11189
Why not wrap it in an abstraction that you can mock?
class RouterFactory {
Router createRouter(Object param) {
return Router.router(param);
}
}
And use it in your class
class YourClass {
private final RouterFactory routerFactory;
YourClass(RouterFactory routerFactory) {
this.routerFactory = routerFactory;
}
void doSth() {
// do sth
}
}
Then you can mock the RouterFactory without any problems and you don't have to use Powermock.
Upvotes: 0