Spring Rest控制器的Mock Principal

时间:2017-08-08 07:05:41

标签: java spring

我有以下REST控制器:

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

CustomUserDetails包含多个字段,包括usernamepassword

我想在控制器方法中模拟主体(或从测试传递到控制器方法)。我该怎么办?我看了很多帖子,但他们都没有回答这个问题。

修改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);
}

1 个答案:

答案 0 :(得分:4)

您可以在测试用例中模拟一个主体,对其设置一些期望,然后使用MockHttpServletRequestBuilder.principal()将该模拟传递给mvc调用。

我已经更新了你的例子:

@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);
}

使用这种方法,您的控制器方法将接收模拟的Principal实例。我已在本地验证了此行为。