【发布时间】:2022-01-22 19:21:37
【问题描述】:
有没有办法在 服务 中而不是在控制器中测试 Spring Security (5.6.x) 的安全注释?
我看到了很多解决方案,但是没有一个适合我。我怀疑版本(5.6.x)中的交易。 我尝试了文档 (4.2.2.) 中的解决方案,但它对我不起作用。
我当前的测试注释:
@ExtendWith(MockitoExtension.class)
@SecurityTestExecutionListeners
@EnableMethodSecurity(securedEnabled = true)
class PostAuthTest {
@InjectMocks
private PostAuthService service;
@Test
@WithAnonymousUser
void testSuperSecureMethod() {
assertThrows(ForbiddenClassException.class, () -> service.someSuperSecureMethod());
}
}
测试类:
public class PostAuthService {
@PostAuthorize("returnObject.length() > 5")
public String someSuperSecureMethod() {
return "123";
}
}
当我在应用程序中运行服务的安全注释时,它们可以正常工作。
我更喜欢在服务的测试中避免使用SpringBootTest 注释,因为这里看起来势不可挡。我尝试使用身份验证和返回的对象模拟来测试PostAuthorize。
有什么想法吗?
【问题讨论】:
-
Spring Security reference documentation 中有一个很棒的测试部分。
-
如何创建
Service实例?您必须将其添加到您的应用程序上下文中。 -
@dur,您的解决方案有效。 bean 不在应用程序上下文中,InjectMocks 在应用程序上下文之外创建一个实例。我已将 bean 添加到 ContextConfiguration,因此测试现在可以正常工作
标签: java spring spring-security