Reputation: 155
I have an api call as:
@RequestMapping(value = "/course", method = RequestMethod.GET)
ResponseEntity<Object> getCourse(HttpServletRequest request, HttpServletResponse response) throwsException {
User user = userDao.getByUsername(request.getRemoteUser());
}
I'm getting the user null when I call this from the test class like:
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();
When I debug request object I can see remoteUser=null
. So how can I pass the value to remote user?
Upvotes: 5
Views: 8109
Reputation: 316
In Kotlin to set remoteUser
in the MockHttpServletRequest
use the @WithMockUser
annotation.
Add the dependency testImplementation("org.springframework.security:spring-security-test:4.0.4.RELEASE")
in build.gradle.kts
Add the @WithMockUser(username = "user")
in the test
@WebMvcTest(controllers = [DossierController::class])
internal class DossierControllerTest {
@MockkBean
lateinit var request: MockHttpServletRequest
@Test
@WithMockUser(username = "user")
fun createDossierTest() {
}
}
Upvotes: 0
Reputation: 48133
You can use RequestPostProcessor
in order to modify the MockHttpServletRequest
in any fashion you want. In your case:
mockMvc.perform(get("/course").with(request -> {
request.setRemoteUser("USER");
return request;
})...
And if you're stuck with older versions of Java:
mockMvc.perform(get("/course").with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setRemoteUser("USER");
return request;
}
})...
Upvotes: 16