将HttpServletRequest中的remoteUser值传递给mockmvc执行测试

时间:2016-02-02 19:55:53

标签: spring mockito spring-test spring-test-mvc

我有一个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。那么如何将值传递给远程用户?

2 个答案:

答案 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

  1. testImplementation("org.springframework.security:spring-security-test:4.0.4.RELEASE")中添加依赖项build.gradle.kts

  2. 在测试中添加@WithMockUser(username = "user")

@WebMvcTest(controllers = [DossierController::class])
internal class DossierControllerTest {
  
  @MockkBean
  lateinit var request: MockHttpServletRequest
  
  @Test
  @WithMockUser(username = "user")
  fun createDossierTest() {

  }
}
相关问题