Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Principal for Spring Rest controller

Tags:

java

spring

I have the following REST controller:

@RequestMapping(path = "", method = RequestMethod.GET)
public ExtendedGetUserDto getCurrentUser(Principal principal) {
    CustomUserDetails userDetails = userDetailsService.loadByUsername(principal.getName())
    // .....
}

CustomUserDetails has a number of fields, including username and password

I want to mock principal in the controller method (or pass from test to the controller method). How should I do that ? I read many posts, but none of them actually answered this question.

Edit 1

@Test
public void testGetCurrentUser() throws Exception {

    RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
            USER_ENDPOINT_URL).accept(MediaType.APPLICATION_JSON);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();

    MockHttpServletResponse response = result.getResponse();
    int status = response.getStatus();
    Assert.assertEquals("response status is wrong", 200, status);
}
like image 624
Arian Avatar asked Aug 08 '17 07:08

Arian


1 Answers

You can mock a principal in your test case, set some expectations on it and then pass this mock down the mvc call using MockHttpServletRequestBuilder.principal().

I've updated your example:

@Test
public void testGetCurrentUser() throws Exception {
    Principal mockPrincipal = Mockito.mock(Principal.class);
    Mockito.when(mockPrincipal.getName()).thenReturn("me");

    RequestBuilder requestBuilder = MockMvcRequestBuilders
        .get(USER_ENDPOINT_URL)
        .principal(mockPrincipal)
        .accept(MediaType.APPLICATION_JSON);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();

    MockHttpServletResponse response = result.getResponse();
    int status = response.getStatus();
    Assert.assertEquals("response status is wrong", 200, status);
}

With this approach, your controller method will receive the mocked instance of Principal. I have verified this behaviour locally.

like image 179
glytching Avatar answered Sep 24 '22 05:09

glytching