我正在努力为方面代码编写单元测试用例。请找到所有相应的代码。
自定义注解-
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface WriteAccessAuthorization{
boolean isAdmin() default false;
}
纵横比代码-
@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();
}
...
}
在这里,我在方法的最后一行获得了NPE。在这里,方法.getAnnotation()返回NULL,即使我们在Junit测试方法中模拟它。
请找到junit测试用例代码-
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");
}
}
在许多博客或stackoverflow
答案中,都提到在您的注解中有运行时策略,但在我的例子中,它已经被放置了。如果还需要什么,请告诉我。
暂无答案!
目前还没有任何答案,快来回答吧!