1

I'm using Mockito (3.6.x) for my unit tests in Spring Boot (2.4.x) with JUnit 4. I need to test the next code block:

MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
CustomAnnotation customAnnotation = method.getAnnotation(CustomAnnotation.class);

I have tried this with other solutions (also with StackOverflow help), and I am working with PowerMockito now.

When I do:

MethodSignature methodSignature = PowerMockito.mock(MethodSignature.class);
PowerMockito.when((MethodSignature) proceedingJoinPointTest.getSignature()).thenReturn(methodSignature);
Method method = PowerMockito.mock(Method.class);

It works. But when I do:

CustomAnnotation customAnnotation = PowerMockito.mock(CustomAnnotation.class);
PowerMockito.when(method.getAnnotation(CustomAnnotation.class)).thenReturn(customAnnotation);

It fails. Also I tried with:

PowerMockito.when(method.getAnnotation(CustomAnnotation.class)).thenReturn(new CustomAnnotation() {
    // Implementation
});

But it fails too. Do you have any idea to solve it?

Thank you soo much!

  • Have you considered testing this without mocking the reflection code? Inside your test class define a static nested class with a method annotated with `@CustomAnnotation`. Then you only need to mock or fake `proceedingJoinPoint.getSignature()` – NamshubWriter Jul 28 '21 at 02:48
  • Yes, I have. But according to OWASP Top 10, when I define a static nested class with the methods I need, I do `when(proceedingJoinPoint.getSignature().getMethod()).thenReturn(NestedClass.class.getMethod('methodName'););` and that is a BAC (Broken Access Control), and it says that attackers could extract info or invoke inner logic. That was the reason I left this option. Thanks @NamshubWriter. – Kevin Riaño Aug 20 '21 at 17:33
  • I personally wouldn't be worried about if that kind of security issue in your tests. If there's no way do disable the warning for tests, then have your test code test against a top-level package-scope or public class in the same directory as the test. My larger point is that you shouldn't mock the reflection APIs. – NamshubWriter Aug 22 '21 at 05:09
  • Ok, I will do that. Thanks a lot @NamshubWriter – Kevin Riaño Sep 28 '21 at 13:39

0 Answers0