Spring Boot 使用MockMvc进行单元测试

15 篇文章 1 订阅
1 篇文章 0 订阅

1简介

持有TTD(测试驱动开发)理念的开发人员认为,单元测试在编程过程中扮演了举足轻重的地位,虽然看起来花费了编码时间,但却能够极大的减少调试时间,是非常重要的开发过程。

2对Spring Boot程序进行单元测试

2.1使用Spring Initializer构造web程序

以Web为例,在Core页面中勾选Web即可。下一步,直到构造项目完成即可。很简单,不再赘述

2.2在pom文件中引入fastjson包

pom文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!--仅需手动导入fastjson包即可,spring-boot-starter-test自动导入-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

注意:由于勾选了核心模块web,因此pom文件会自动导入spring-boot-starter-web和spring-boot-starter-test,代码只需要导入alibaba的jar包fastjson即可。

2.3项目结构

在项目中添加类型TestUnit,并为该类型中添加两个简单的Http请求,一个Get请求,一个Post请求。
项目结构如下:
在这里插入图片描述

2.3.1 TestUnit内容

package com.example.demo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 单元测试控制类
 *
 * @Owner:
 * @Time: 2019/3/12-22:35
 */
@RestController
public class TestUnit {

    @RequestMapping("/")
    public String hello() {
        return "hello";
    }

    @PostMapping(value = "/page", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getPageList(@RequestBody JSONObject pageObj) {
        int pageNo = pageObj.getIntValue("pageNo");
        int pageSize = pageObj.getIntValue("pageSize");
        //handle pageObj

        JSONArray list = new JSONArray();
        list.fluentAdd(5).fluentAdd(6);
        JSONObject result = JSONObject.parseObject(pageObj.toJSONString());
        result.put("list", list);
        return result.toJSONString();
    }
}

在上述Controller类中,添加了两个函数,一个名为hello的get请求,一个为需要传入JSON对象的getPageList请求。
这也比较简单,不再赘述。

2.3.2通过IDEA自带的Test Restful Web Service测试代码

IDEA自带一个良好的工具Test Restful Web Service,位置在

Tools -> HTTP Client -> TestRestful Web Service

由于get请求没有参数,很简单,测试部再赘述,主要测试Post请求,
如果在其中不指定Content-Type的header,
在这里插入图片描述
则服务弹出如下的结果:
在这里插入图片描述
可以看出结果status为415,Unsupported Media Type,

{
	"timestamp": "2019-03-12T15:45:54.808+0000",
	"status": 415,
	"error": "Unsupported Media Type",
	"message": "Content type '*/*;charset=UTF-8' not supported",
	"path": "/page"
}

因此,如果在Controller接口中指定了@RequestBody JSONObject,则一定要指定Content-Type
若指定了Content-Type为application/json,则接口会成功执行,弹出如下的结果:
在这里插入图片描述
可以看到响应中已经有了结果

{
	"pageNo": 1,
	"pageSize": 10,
	"list": [5, 6]
}

2.4TestUnitTest类,编写测试代码

2.4.1 测试代码

在IDEA集成了JUnit测试的基础在类TestUnit上点击

Ctrl + Alt + T

即可自动生成测试框架。
该类的内容如下:

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
@AutoConfigureMockMvc
public class TestUnitTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mvc;
    JSONObject page = null;
    @Before
    public void setUp() throws Exception {
        page = new JSONObject();
        page.fluentPut("pageNo", 1);
        page.fluentPut("pageSize", 10);
        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void hello() throws Exception{
        MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/"))
                .andReturn();
        int status = result.getResponse().getStatus();
        String contentType = result.getResponse().getContentType();
        String url = result.getRequest().getRequestURI();
        String content = result.getResponse().getContentAsString();
        int contentLength = result.getResponse().getContentLength();
        assertEquals(HttpStatus.OK.value(), 200);
        assertEquals("hello", content);


    }

    @Test
    public void getPageList() throws Exception {
        MvcResult result = mvc.perform(MockMvcRequestBuilders.post("/page")
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .content(page.toJSONString()))
        .andReturn();
        int status = result.getResponse().getStatus();
        String contentType = result.getResponse().getContentType();
        String url = result.getRequest().getRequestURI();
        String content = result.getResponse().getContentAsString();
        int contentLength = result.getResponse().getContentLength();
        assertEquals(HttpStatus.OK.value(), 200);
        assertEquals("/page", url);
        assertEquals(MediaType.APPLICATION_JSON_UTF8_VALUE,contentType);
        JSONObject res = JSONObject.parseObject(content);
        assertEquals(2,res.getJSONArray("list").size());

    }
}

注意, 必须在@SpringBootTest注解中指定(classes = DemoApplication.class)

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test

2.4.2 代码分析

在这里插入图片描述

2.4.3 测试结果

在这里插入图片描述
可以看到两个测试用例均通过了测试。

3总结

单元测试用例很重要,在步入高级程序员的过程中,必不可少。

4参考

《重构 改善既有代码的设计》之JUnit测试框架以及IDEA与JUnit整合

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 项目的单元测试通常使用 JUnit 和 Spring Test 模块。下面是一个简单的 Spring Boot 单元测试示例代码: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.SqlConfig; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringJUnitConfig @SpringBootTest @AutoConfigureMockMvc @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) @DataJpaTest public class UserControllerTest { @Autowired private MockMvc mockMvc; @Test @Sql(scripts = "/data.sql", config = @SqlConfig(encoding = "UTF-8")) public void getUserByIdTest() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users/1")) .andExpect(status().isOk()) .andReturn(); String content = result.getResponse().getContentAsString(); assertEquals("{\"id\":1,\"name\":\"John\",\"age\":30}", content); } } ``` 上面的示例代码演示了如何编写一个测试 `UserController` 的单元测试。在 Spring Boot 中,我们通常使用 `@SpringBootTest` 注解来启动整个应用程序上下文,使用 `@AutoConfigureMockMvc` 注解来注入 MockMvc 对象,以便测试控制器的 RESTful API。我们还可以使用 `@DataJpaTest` 注解和 `@AutoConfigureTestDatabase` 注解来配置测试数据库,以便测试持久化操作。在这个例子中,我们还使用了 `@Sql` 注解来执行 SQL 脚本,以便在测试前准备测试数据。 总的来说,Spring Boot单元测试相比传统的单元测试更加复杂,但是也更加强大和灵活。我们可以根据具体的测试需求来选择合适的测试工具和策略。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值