我正在使用@PreAuthorize保护网络请求
@PreAuthorize("(@assessmentAuthService.canViewAssessment(#id))")
AssessmentAuthService是spring自动创建的,但是我需要从单元测试中注入一个模拟对象。
private final AssessmentService assessmentService;
@Inject
public AssessmentAuthorizationServiceImpl(AssessmentService assessmentService) {
this.assessmentService = assessmentService;
}
这是因为我希望assessmentService.getById(assessmentId)返回一个模拟对象。 我已经尝试过设置它,但它不起作用:
ReflectionTestUtils.setField(assessmentAuthorizationService,
"assessmentService", mockAssessmentService);
答案 0 :(得分:0)
我试图用ReflectionTestUtils.setField将一个模拟注入到AssessmentAuthorizationService中,但我没有意识到spring bean是代理。在设置字段之前,我必须使用此方法来解包代理。
class TestUtils {
...
public static Object unwrapService(Object service) throws Exception {
final boolean aopProxy = AopUtils.isAopProxy(service);
final boolean instanceCheck = service instanceof Advised;
if (aopProxy && instanceCheck) {
Object target = ((Advised) service).getTargetSource().getTarget();
return target;
}
return null;
}
}
我这样做后就有效了。我可以将字段设置为模拟并定义我想要的行为。
ReflectionTestUtils.setField(TestUtil.unwrapService(assessmentAuthorizationService),
"assessmentService", mockAssessmentService);
when(mockAssessmentService.getById(eq(2L))).thenReturn(Optional.of(assessment));