私のプロジェクトでは、anglejsフロントエンドに対応するREST APIエンドポイントであるkotlinを使用しようとしています。そして、私はAPIのドキュメントにspring rest docを使用します。Spring統合テスト - AuthenticationPrincipalが注入されていません
移行中に、セキュリティコンテキストがテストケースに挿入されていないことがわかりました。 (ほとんどのIntelliJにより変換)mockito-kotlinと
Testクラス:
@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
がnullではないが、userDetail.userId
はNULLです。したがって、テストクラスの認証がコントローラコールに注入されていないように見えます。
私は何か間違ったことをしましたか、それを修正する方法はありますか?
私の間違いは、これはコッリン固有の問題ではありません。 Javaは同じように動作します。しかし、kotlinではgetUserInfoの最初のパラメータをnullにできませんでしたが、SpringによってuserDetailを正しく注入する方法はありますか? – klc