首页 > 其他分享 >Spring boot controller单元测试

Spring boot controller单元测试

时间:2022-12-16 10:44:48浏览次数:34  
标签:MsgSceneParamItem String Spring boot public controller new com class

工具准备

测试框架依赖包

<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出一个对象,如果不提供默认构造方法,就会序列化失败!

标签:MsgSceneParamItem,String,Spring,boot,public,controller,new,com,class
From: https://www.cnblogs.com/dreamerwblog/p/16986668.html

相关文章

  • Spring Boot + vue-element 开发个人博客项目实战教程(二十一、个人介绍、公告管理、标
    ⭐作者简介:码上言⭐代表教程:​​SpringBoot+vue-element开发个人博客项目实战教程​​⭐专栏内容:零基础学Java、个人博客系统文章目录​​一、个人介绍​​​​二、......
  • Spring REST Docs文档(二)
    自定义请求和响应在某些情况下,您可能不希望完全按照发送的方式记录请求或完全按照收到的响应记录响应。SpringRESTDocs提供了许多预处理器,可用于在记录请求或响应之前对......
  • Spring Batch - 批处理架构
    SpringBatch的设计考虑了可扩展性和不同的最终用户群体。这种分层体系结构突出了三个主要的高级组件:应用程序、核心和基础结构。应用程序包含所有批处理作业和编写的自定......
  • Spring Batch -批处理的域语言
    对于任何有经验的批处理架构师,批处理的总体概念用于春季批次应该是熟悉和舒适的。有“作业”和“步骤”和开发人员提供的处理单元称为和。然而由于Spring模式、操作......
  • Spring Batch -配置和运行作业
    在域部分,整体讨论了体系结构设计,使用下图作为指导:图1.批量构造型虽然这个对象看起来很简单容器的步骤,您必须了解许多配置选项。此外,您必须考虑许多选项如何运行a及其......
  • springMVC08(REST风格的“入门案例”)
    一、用REST风格,来演示"增、删、改、查"操作。1.1:增POST1.1.1:用PostMan测试:增POST:代码块@RequestMapping(value="/users",method=RequestMethod.POST)@R......
  • SpringMvc的基础
     首先SpringMvc是一款实现MVC模型的轻量级web框架,主要用在写那个controller也就是控制器,也就是表现层代码的书写,以前使用Servlet来写这个表现层,现在的话使用SpringMvc就......
  • 15 个很棒的 Bootstrap UI 界面编辑器
    [导读]​​BootstrapMagic​​​​BootSwatchr​​​​BootstrapLiveEditor​​​​FancyBoot​​ ​​StyleBootstrap​​​​Lavish​​​​BootstrapThemeRol......
  • Spring Boot
    SpringBoot技术分析与运用—抢购网项目在互联网兴起的时代,高可用、高性能和高可扩展性的项目架构方式将是一个必然趋势,而微服务则是目前最好的选择。微服务是更细粒度的......
  • 2.Spring Boot项目环境搭建
    2.1环境要求JDK1.7及以上版本,Maven3.2及以上版本,IDEA14及以上版本2.2搭建步骤第一步:打开IDEA,选择File,新建project或者module,弹出如图2.1所示的窗口   这里JDK默......