我有一个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
。那么如何将值传递给远程用户?
答案 0 :(得分:10)
您可以使用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;
}
})...
答案 1 :(得分:0)
在Kotlin中,使用remoteUser
批注在MockHttpServletRequest
中设置@WithMockUser
。
在testImplementation("org.springframework.security:spring-security-test:4.0.4.RELEASE")
中添加依赖项build.gradle.kts
在测试中添加@WithMockUser(username = "user")
@WebMvcTest(controllers = [DossierController::class])
internal class DossierControllerTest {
@MockkBean
lateinit var request: MockHttpServletRequest
@Test
@WithMockUser(username = "user")
fun createDossierTest() {
}
}