I wanted to do so custom logic(Record the request and response) on some routes. Based on some research I came decided to use AnnotationBased RequestInterceptor. This is my code for interceptor.
public class CustomInterceptor extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(final HttpServletRequest request,
final HttpServletResponse response,
final Object handler,
final Exception ex) {
if (handler != null && handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
CustomRecord annotation = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), CustomRecord.class);
if (annotation != null) {
// Record Request and Response in a File.
}
}
Now this class is working as expected but I was unable to unit test this function.
- I first thought of trying a creating an HandlerMethod Object but I did not get anywhere.
-
Second I tried to use PowerMokito. This was my test code:
@RunWith(PowerMockRunner.class) @PrepareForTest(CustomInterceptor.class) @PowerMockIgnore("javax.management.*") public class CustomInterceptorTest { @Test public void restAnnotationRecording_negetivecase() { HandlerMethod mockHandler = mock(HandlerMethod.class); PowerMockito.mockStatic(AnnotationUtils.class); when(AnnotationUtils.getAnnotation(mockHandler.getMethod(), CustomRecord.class).thenReturn(null); // Verify file is not saved } // A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() methodcannot be saved. @Test public void restAnnotationRecording_happycase() { HandlerMethod mockHandler = mock(HandlerMethod.class); PowerMockito.mockStatic(AnnotationUtils.class); when(AnnotationUtils.getAnnotation(mockHandler.getMethod(), CustomRecord.class).thenReturn(mockAnnotation); // Verify file is saved } }
- This gives an Error A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods.
I wanted to check if there is any method to test the Interceptor. I am a newbie in Java, thanks for help.
Aucun commentaire:
Enregistrer un commentaire