Spring Rest控制器的模拟主体 [英] Mock Principal for Spring Rest controller

查看:76
本文介绍了Spring Rest控制器的模拟主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下REST控制器:

I have the following REST controller:

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

CustomUserDetails具有许多字段,包括usernamepassword

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆