【发布时间】:2016-10-04 11:17:35
【问题描述】:
我正在尝试在我的项目中使用 kotlin,它是为 angularjs 前端提供服务的 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 为空。所以看起来测试类中的身份验证没有注入到控制器调用中。
我是不是做错了什么,或者如何解决?
【问题讨论】:
-
我的错,这不是 kotlin 特定的问题。 Java 的行为相同。但是在 kotlin 中,我使 getUserInfo 的第一个参数不可为空,有没有办法通过 Spring 正确注入 userDetail?
标签: kotlin spring-test spring-test-mvc