我有一个 api 调用:
@RequestMapping(value = "/course", method = RequestMethod.GET)
ResponseEntity<Object> getCourse(HttpServletRequest request, HttpServletResponse response) throwsException {
User user = userDao.getByUsername(request.getRemoteUser());
}
当我从测试类调用它时,我得到用户 null,例如:
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteUser()).thenReturn("test1");
MvcResult result = mockMvc.perform( get( "/course")
.contentType(MediaType.APPLICATION_JSON)
.andExpect( status().isOk() )
.andExpect( content().contentType( "application/json;charset=UTF-8" ) )
.andReturn();
当我调试请求对象时,我可以看到remoteUser=null
.那么如何将值传递给远程用户呢?
您可以使用RequestPostProcessor
以所需的任何方式修改MockHttpServletRequest
。在您的情况下:
mockMvc.perform(get("/course").with(request -> {
request.setRemoteUser("USER");
return request;
})...
如果你坚持使用旧版本的Java:
mockMvc.perform(get("/course").with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setRemoteUser("USER");
return request;
}
})...
在 Kotlin 中,要在MockHttpServletRequest
中设置remoteUser
,请使用@WithMockUser
注释。
-
在
build.gradle.kts
中添加依赖项testImplementation("org.springframework.security:spring-security-test:4.0.4.RELEASE")
-
在测试中添加
@WithMockUser(username = "user")
@WebMvcTest(controllers = [DossierController::class])
internal class DossierControllerTest {
@MockkBean
lateinit var request: MockHttpServletRequest
@Test
@WithMockUser(username = "user")
fun createDossierTest() {
}
}