spring boot测试中如何配置HandlerMethodArgumentResolver

Man*_*anu 5 junit spring-mvc-test spring-boot spring-boot-test

我正在为带有 spting boot 的控制器编写一个单元@WebMvcTest

使用@WebMvcTest,我将能够注入一个MockMvc对象,如下所示:-

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@WebMvcTest
class MyControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void my_controller_test() throws Exception {
       mockMvc.perform(post("/create-user"))
              .andExpect(status().isCreated());
    }
}
Run Code Online (Sandbox Code Playgroud)

在控制器中,我Principal使用 spring 注入一个参数HandlerMethodArgumentResolver。请告诉我如何使用 编写单元测试MockMvc,以便我可以注入模拟Principal对象作为控制器方法中的参数。

自动配置的 Spring MVC 测试部分解释了带有注释的测试@WebMvcTest将扫描HandlerMethodArgumentResolver. 所以我创建了一个 bean,它扩展HandlerMethodArgumentResolver并返回模拟Principal对象,如下所示。

@Component
public class MockPrincipalArgumentResolver implements HandlerMethodArgumentResolver {
   @Override
   public boolean supportsParameter(MethodParameter parameter) {
     return parameter.getParameterType().equals(Principal.class);
   }

   @Override
   public Object resolveArgument(MethodParameter parameter...) throws Exception {
     return new MockPrincipal();
   }
 }
Run Code Online (Sandbox Code Playgroud)

但参数仍然MockPrincipal没有传递给控制器​​方法。

Spring 启动版本:- 1.4.5.RELEASE

M. *_*num 1

您正在使用MockMvc呼叫您的控制器。这样,您就必须准备好请求,其中包含参数、正文、URL 以及主体等内容。您未指定的内容将不会被包括在内(您现在基本上是在没有经过身份验证的主体的情况下进行调用)。

一般来说, Spring MVC 测试对MockMvc的支持记录在参考指南中。

有关更详细的信息,请检查用于构建模拟请求的组件MockHttpServletRequestBuilder。这就是你的post方法将返回的内容,这应该是一个调用MockHttpServletRequestBuilders.post(并且可能是代码中的静态导入)。之后的 [CTRL]+[SPACE](或者您最喜欢的代码完成快捷方式在您的 iDE 中)post()将让您了解可用的内容。

@Test
public void my_controller_test() throws Exception {
   mockMvc.perform(post("/create-user").principal(new MockPrincipal())
          .andExpect(status().isCreated());
}
Run Code Online (Sandbox Code Playgroud)

像上面这样的东西应该可以解决问题。