我有以下REST控制器:
@RequestMapping(path = "", method = RequestMethod.GET)
public ExtendedGetUserDto getCurrentUser(Principal principal) {
CustomUserDetails userDetails = userDetailsService.loadByUsername(principal.getName())
// .....
}
CustomUserDetails
包含多个字段,包括username
和password
我想在控制器方法中模拟主体(或从测试传递到控制器方法)。我该怎么办?我看了很多帖子,但他们都没有回答这个问题。
修改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);
}
答案 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
实例。我已在本地验证了此行为。