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

10,901

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.

Share:
10,901

Related videos on Youtube

Matt Lachman
Author by

Matt Lachman

Java web developer since 2004, Sun Certified Java Programmer since 2007. I'm a Senior Software Engineer in the Greater Rochester Area with most of my work being at Thomson Reuters. My technology interests include: Grails, simple user scripts / bookmarklets, and PowerMock, Java backend, and React frontend.

Updated on June 04, 2022

Comments

  • Matt Lachman
    Matt Lachman almost 2 years

    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:

  • Matt Lachman
    Matt Lachman about 12 years
    Yes, it looks like a similar issue. I ended up going the route of creating a Method object normally from a mock, then verifying that the method was invoked on the mock. Thanks!