如何在spring boot test

时间:2017-07-17 10:35:51

标签: spring-boot junit spring-mvc-test 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());
    }
}

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

结果Auto-configured Spring MVC tests解释了使用@WebMvcTest注释的测试将扫描HandlerMethodArgumentResolver的bean。所以我创建了一个扩展HandlerMethodArgumentResolver并返回模拟Principal对象的bean,如下所示。

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

但是Argument MockPrincipal仍未传递给控制器​​方法。

Spring boot版本: - 1.4.5.RELEASE

1 个答案:

答案 0 :(得分:1)

您正在使用// Show Filter checklist onClick handleShowFilterList(id) { if(this.state.filterListShow !== id) { this.setState({ filterListShow: id, active: false }) } else { this.setState({filterListShow: false}) } } 来呼叫您的控制器。有了这个,你必须准备请求与参数,正文,URL和主体。您未指定的内容将不包括在内(您现在基本上在没有经过身份验证的校长的情况下进行呼叫)。

一般情况下,参考指南中记录了对MockMvc的Spring MVC测试支持。

有关更详细的信息,请检查用于构建模拟请求的组件MockHttpServletRequestBuilder。这是MockMvc方法将返回的内容,应该调用post(可能是代码中的静态导入)。在MockHttpServletRequestBuilders.post之后,[CTRL] + [SPACE](或您喜欢的任何代码完成捷径在您的iDE中)将为您提供有关可用内容的一些信息。

post()

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