SpringBoot Controller单元测试

工具准备

测试框架依赖包

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version>RELEASE</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter-test</artifactId>
      <version>3.5.2</version>
    </dependency>

测试基础类

@Configuration
@AutoConfigureMybatisPlus
@ImportAutoConfiguration
@MapperScan(basePackages = "com.xxx.osp.basic.mapper.**.*")
@EnableWebMvc
public class TestConfiguration {
}


@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@AutoConfigureMockMvc
@WebAppConfiguration
public class BaseControllerTest {

  @Autowired
  public MockMvc mockMvc;

  public String doPost(String url, String json) throws Exception {
    ResultActions perform = mockMvc.perform(MockMvcRequestBuilders.post(url)
        .content(json)
        .contentType(MediaType.APPLICATION_JSON)
    );
    return print(perform);
  }

  public String doGet(String url, Map<String, String> params) throws Exception {
    MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(url)
        .contentType(MediaType.APPLICATION_FORM_URLENCODED);
    if (!params.isEmpty()) {
      params.forEach((key, value) -> {
        requestBuilder.param(key, value);
      });
    }
    ResultActions perform = mockMvc.perform(requestBuilder);
    return print(perform);
  }

  public String print(ResultActions resultActions) throws Exception {
    String result = resultActions.andExpect(MockMvcResultMatchers.status().isOk())
        .andDo(MockMvcResultHandlers.print())
        .andReturn().getResponse().getContentAsString();
    System.out.println("resultData: " + result);
    return result;
  }

}

测试类编写

@Import({MsgSceneServiceImpl.class, MsgSceneController.class})
public class MsgSceneControllerTest extends BaseControllerTest {

  @Test
  public void testCreate() throws Exception {
    String url = "/v1/msg/scene/create";
    List<MsgSceneParamItem> list = new ArrayList<>();
    list.add(new MsgSceneParamItem("名称", "name"));
    list.add(new MsgSceneParamItem("账号", "account"));
    list.add(new MsgSceneParamItem("签名", "sign"));
    MsgSceneCreateVO vo = new MsgSceneCreateVO();
    vo.setCode("0003")
        .setType(4)
        .setName("创建验证")
        .setTag("验证登陆")
        .setRemark("备注")
        .setParam(list);
    String json = JsonUtils.object2Json(vo);
    System.out.println("参数:" + json);
    System.out.println("参数结束");
    String result = doPost(url, json);
    System.out.println("结果返回:");
    System.out.println(result);
  }
}

MsgSceneController需要注入MsgSceneServiceImpl,所以Import进来

记录报错解决:

  • Content type ‘application/json’ not supported,如果报这个错误,看看TestConfiguration类是不是没有加@EnableWebMvc注解,加上即可解决
  • 参数传递错误解决
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.xxx.osp.basic.model.bo.msg.MsgSceneParamItem]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.xxx.osp.basic.model.bo.msg.MsgSceneParamItem` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (PushbackInputStream); line: 1, column: 78] (through reference chain: com.xxx.osp.basic.model.vo.msg.request.MsgSceneCreateVO["param"]->java.util.ArrayList[0])

报错提示:类MsgSceneParamItem没有默认构造方法,添加一个无参数构造就好了,因为在将参数进行反序列化的时候用的就是无参构造new出一个对象,如果不提供默认构造方法,就会序列化失败!

猜你喜欢

转载自blog.csdn.net/wwrzyy/article/details/128339145