Mocking Reflection based calls

后端 未结 2 1448
悲&欢浪女
悲&欢浪女 2020-12-16 15:23

I am trying to mock some reflection based methods. Below you can see the details,

Class Under Test

public class TracerLog {
    @AroundInvoke
    pu         


        
相关标签:
2条回答
  • 2020-12-16 15:54

    Yeah the problem is that mockContext.getMethod() is going to return null. So every time you run this, then call something on the result (getDeclaringClass() or getName()) you'll get the NPE. You probably want to use the RETURNS_DEEP_STUBS default answer, when you set up the mock. Something like

    @Mock( answer = RETURNS_DEEP_STUBS ) private InvocationContext mockContext; 
    

    should do the trick.

    0 讨论(0)
  • 2020-12-16 16:09

    You need a Method object and a Class object. As per your comment, Mockito cannot mock a Method, so you'll need a real one. I haven't tested this, but I believe this would work. Instead of:

    when(mockContext.getMethod().getName()).thenReturn("someMethod");
    when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
    

    You need:

    // any method will do, but here is an example of how to get one.
    Method testMethod = this.getClass().getMethod("logCallTest");
    
    when(mockContext.getMethod()).thenReturn(testMethod);
    

    Obviously, getName() will not return "someMethod" anymore and getDeclaringClass().getName() will return the name of this test class (in the example), but although you couldn't pick what they return, what they return is still deterministic, so you should be able to verify anything you need. (Of course, if you needed to spy or verify that a call was made on the Method object itself, you're still stuck.)

    0 讨论(0)
提交回复
热议问题