spring-boot - 未在测试中评估的服务上的反应性 @PreAuthroize
问题描述
我想测试访问被服务拒绝,但未@PreAuthorize
评估。我可能缺少一些配置,但我不知道是什么。
这是服务
@Service
class FooServiceImpl : FooService {
@PreAuthorize("denyAll")
suspend fun bar() {
println("I am not accessible")
}
}
这是我期望的测试AccessDeniedException
:
@ExtendWith(SpringExtension::class, MockKExtension::class)
@Import(TestSecurityConfig::class)
internal class FooServiceImplTest {
@InjectMockKs
lateinit var fooService: FooServiceImpl
@Test
fun shouldDeny() {
runBlocking {
assertThrows<Exception> {
fooService.bar()
}
}
}
}
这是我导入的测试配置:
@TestConfiguration
@EnableReactiveMethodSecurity
@EnableWebFluxSecurity
class TestSecurityConfig {
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? {
return http {
csrf { disable() }
formLogin { disable() }
httpBasic { disable() }
authorizeExchange {
authorize(anyExchange, authenticated)
}
}
}
}
测试失败:
Expected java.lang.Exception to be thrown, but nothing was thrown.
我也尝试添加@EnableGlobalMethodSecurity(prePostEnabled = true)
(但据我了解,在使用时不需要这样做@EnableReactiveMethodSecurity
?)并且还尝试直接在测试类上添加注释。
解决方案
我忘了考虑如何创建被测服务。在问题的设置中@InjectMockks
,当然直接创建实例而不是在春季比赛中。没有上下文,就没有安全性交织在一起。
@ExtendWith(SpringExtension::class, MockKExtension::class)
@Import(TestSecurityConfig::class)
@ContextConfiguration(classes = [FooServiceImpl::class])
internal class FooServiceImplTest {
@Autowired
lateinit var fooService: FooService
// ...
}
注 1:FooServiceImpl
now 是通过 the 选择的@ContextConfiguration
,然后@Autowired
tofooService
是通过引用它的界面来选择的。
注意 2:以前我使用@MockK
的是FooService
. 他们现在必须是@MockKBean
s。
推荐阅读
- c++ - 无法在 C++ 中打印矢量对象数据成员值
- javascript - 在 Intersection Observer API 中定位目标
- amazon-web-services - AWS CloudFomation:无法与 ElasticBeanstalk 一起创建 RDS 资源
- tensorflow - 使用 TensorFlow Quantum 进行多类分类
- javascript - 当我按下提交/播放时,表单上的事件监听器不会触发
- c# - 从另一个方法调用一个方法并传递参数
- javascript - ElectronJS 为每张幻灯片指定程序路径( SlickJs )
- docusignapi - 什么会导致 Docusign Payments 消息“付款设置失败”?
- r - rstudio一列中每个类别的平均值/平均值
- wordpress - 有没有办法在没有插件或编辑标题的情况下在 WordPress 上使用 Google Analytics?