我正在尝试在我的项目中使用kotlin,这是为alterjs前端提供的REST API端点。我使用spring rest doc作为api文档。
迁移时,我发现我的安全上下文未在测试用例中注入。
使用mockito-kotlin测试类(主要由Intellij转换):
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = arrayOf(MockAppConfig::class))
@WebAppConfiguration
class UserLoginDocumentation {
@get:Rule
var restDocumentation = JUnitRestDocumentation("target/generated-snippets")
private var mockMvc: MockMvc? = null
@Autowired
private val context: WebApplicationContext? = null
@Before
fun setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context!!)
.apply<DefaultMockMvcBuilder>(documentationConfiguration(this.restDocumentation)
.uris().withScheme("https").withHost("myhost.com").withPort(443)).build()
val authentication = TestingAuthenticationToken(MyUserDetailsService.MyUserDetails(1L), null)
SecurityContextHolder.getContext().authentication = authentication
}
@Autowired
lateinit var userLoginService: UserLoginService
@Test
@Throws(Exception::class)
fun loginTest() {
whenever(userLoginService!!.getUserInfo(any(), any(), any())).thenReturn(LoginUserInfo())
this.mockMvc!!.perform(post("/myloginURL/user")//the remaining is not important....
控制器:
@RequestMapping("/myloginURL")
@RestController
class UserLoginController
@Autowired constructor(
val userLoginService: UserLoginService) {
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/user", method = arrayOf(RequestMethod.POST), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getUser(@AuthenticationPrincipal userDetail: MyUserDetails,
request: HttpServletRequest, @RequestParam lang: String): LoginUserInfo? {
return userLoginService.getUserInfo(userDetail.userId, request.getHeader("Authorization"), lang)
}
}
此处userDetail
不为空,但userDetail.userId
为空。因此看起来测试类中的身份验证不会注入控制器调用。
我做错了什么,或者如何解决?
答案 0 :(得分:0)
我应该使用MockMvcBuilders.webAppContextSetup(this.context!!)
.apply(springSecurity(springSecurityFilterChain))
springSecurityFilterChain
已通过@EnableWebSecurity
之后我可以使用我想要的csrf和user,将userDetail注入控制器。