我正在尝试在我的项目中使用kotlin,这是REST API端点服务于angularjs前端。我为我们的api文档使用spring rest doc。Spring集成测试 - AuthenticationPrincipal未注入
迁移时,我发现我的安全上下文没有注入测试用例。用的Mockito-科特林
Test类(主要由转化的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
为空。所以它看起来像测试类中的认证不会被注入到控制器调用中。
我做错了什么,或者如何解决它?
我的错误,这不是一个kotlin特定的问题。 Java的行为相同。然而,在kotlin中,我使getUserInfo的第一个参数不可为空,是否有一种方法可以通过Spring正确地注入userDetail? – klc