I have a class that implements InvocationHandler as below:
public class MyProxyClass implements InvocationHandler
{
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
{
//Do something interesting here
}
}
Using PowerMock & Mockito, I'm trying to pass in a mocked method object in my unit test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Method.class})
public class MyProxyTest
{
MyProxy underTest;
@Test
public void testInvoke() throws Throwable
{
Method mockMethod = mock(Method.class);
//...
}
}
Since Method is final
, I've done the @PrepareForTest
trick but that doesn't seem to cut it. Is this because it's bootstrapped? Am I just going about this wrong?
I've been looking at the below links but there's nothing definitive there:
This method returns annotations that are directly present on this element. This method returns the Class object representing the class or interface that declares the executable represented by this object. This method returns the default value for the annotation member represented by this Method instance.
Mocking a Final Method The mocking of final methods is similar to static methods, except we need to use PowerMockito. mock(class) in place of mockStatic() method. To verify the final method invocations, we can use Mockito. verify() method.
mock() method with ReturnValues: It allows the creation of mock objects of a given class or interface. Now, it is deprecated, as ReturnValues are replaced with Answer. mock() method with String: It is used to create mock objects by specifying the mock names.
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
With PowerMock you can mock a final class, however, although I don't believe it's documented, there are some classes in the java.lang and java.lang.reflect package that you just can't mock because they are too fundamental to how the mocking framework does it's thing.
I think these include (but are probably not limited to) java.lang.Class, java.lang.reflect.Method and java.lang.reflect.Constructor.
However, what are you trying to do that requires a mock method? You could create a real method object easily enough. You could even create a real method object on a dummy class that you could then check to see if it was ever invoked and with what arguments. You just can't use Mockito and Powermock to do it. See if your problem is similar to this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With