I am struggling to write unit test cases for aspect code. Please find the all the respective code.
Custom Annotation -
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface WriteAccessAuthorization{
boolean isAdmin() default false;
}
Aspect Code -
@Aspect
class AccessAspect {
...
...
boolean isAdminForWriteAccess(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
WriteAccessAuthorization writeAccessAuthorization =
method.getAnnotation(WriteAccessAuthorization.class);
return writeAccessAuthorization.isAdminPortal();
}
...
}
Here I am getting NPE in last line of the method. Here method.getAnnotation() is returning null even we are mocking it in Junit test method.
Please find the junit test case code -
class AccessAspectTest {
@Mock private ProceedingJoinPoint joinPoint;
@Mock private MethodSignature methodSignature;
@Mock private Method method;
@Mock private WriteAccessAuthorization writeAccessAuthorization;
@InjectMocks private AccessAspect accessAspect;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
}
@Test
void test_isAdmin()
throws Throwable {
//Given
when(joinPoint.getSignature()).thenReturn(methodSignature);
when(methodSignature.getMethod()).thenReturn(getDeclaredMethod(WriteAccessAuthorization.class));
when(method.getAnnotation(WriteAccessAuthorization.class)).thenReturn(writeAccessAuthorization);
//When
accessAspect.isAdminForWriteAccess(joinPoint);
//Then
verify(joinPoint, times(1)).proceed();
}
@NotNull
private <T> Method getDeclaredMethod(Class<T> clazz) throws NoSuchMethodException {
return clazz.getDeclaredMethod("isAdmin");
}
}
In many blogs or stackoverflow
answers it was mention to have RUNTIME policy in you annotation but in my case it was already placed.
Please let me know if there is anything else required.