I am trying to mock some reflection based methods. Below you can see the details,
Class Under Test
public class TracerLog {
@AroundInvoke
public Object logCall(InvocationContext context) throws Exception {
Logger logger = new Logger();
String message = "INFO: Invoking method - "
+ context.getMethod().getName() + "() of Class - "
+ context.getMethod().getDeclaringClass();
logger.write(message);
return context.proceed();
}
}
Test
public class TracerLogTest {
@Mock
InvocationContext mockContext;
@Mock
Logger mockLogger;
@InjectMocks
private TracerLog cut = new TracerLog();
@BeforeMethod
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void logCallTest() throws Exception {
when(mockContext.proceed()).thenReturn(true);
when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
cut.logCall(mockContext);
verify(mockContext).proceed();
}
}
or
@Test
public void logCallTest() throws Exception {
when(mockContext.proceed()).thenReturn(true);
when(mockContext.getMethod().getName()).thenReturn("someMethod");
when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
cut.logCall(mockContext);
verify(mockLogger).write(anyString());
verify(mockContext).proceed();
}
But, the tests fail with a NullPointerException. I understand that I am doing something wrong against mocking concepts, but I do not understand what it is. Could you please throw some light on it and also suggest me how this method can be tested?
Thanks.