I'm using Mockito for JUnit tests. I have a class A
that is used from the code I want to test:
class A{
public A(){}
public final String a(String x){
return "A.a: " + x;
}
}
I want to replace the method call A.a
with another method call with the same arguments and same type of return value. As you can see, it's not possible to override the method a by extending the class as it is final. So what I have now is another class B
with the method B.b
:
class B{
public B(){}
public String b(String x){
return "B.b: " + x;
}
}
I want to make sure every time when A.a
is called from the code, the return value of B.b
is used instead. Is there a possibility to achieve this with Mockito (something like Mockito.when(A.a(x)).thenReturn(B.b(x));
) but with the same parameter x
, without knowing the value of x
?
It isn't possible to override final methods for Mockito-generated mocks, according to Mockito limits. But you can use Powermock to hack code at runtime so that Mockito can do its job.