Matt Lachman
Matt Lachman

Reputation: 4600

How do I mock java.lang.reflect.Method class in PowerMockito?

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:

Upvotes: 9

Views: 12238

Answers (1)

jhericks
jhericks

Reputation: 5971

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.

Upvotes: 5

Related Questions