Spring Rest控制器的模拟主体 [英] Mock Principal for Spring Rest controller
问题描述
我有以下REST控制器:
I have the following REST controller:
@RequestMapping(path = "", method = RequestMethod.GET)
public ExtendedGetUserDto getCurrentUser(Principal principal) {
CustomUserDetails userDetails = userDetailsService.loadByUsername(principal.getName())
// .....
}
CustomUserDetails
具有许多字段,包括username
和password
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.
编辑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);
}
推荐答案
您可以在测试用例中模拟主体,对其设置一些期望,然后使用MockHttpServletRequestBuilder.principal()
将此模拟传递给mvc调用.
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);
}
使用这种方法,您的控制器方法将收到Principal
的模拟实例.我已经在本地验证了此行为.
With this approach, your controller method will receive the mocked instance of Principal
. I have verified this behaviour locally.
这篇关于Spring Rest控制器的模拟主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!