用RestAssured实现SpringBoot中的单元测试

738 阅读2分钟

关于rest-assured

rest-assured是github上一个开源项目。
地址:github.com/rest-assure…

rest-assured 是一个能够简化测试rest服务的Java DSL,像ruby或者python一样的动态语言去测试和验证http服务。基于java并且兼容了groovy动态语言的特性,使我们像写脚本语言一样去测试http服务。

优点:

简约的接口测试DSL

支持xml json的结构化解析

支持xpath jsonpath gpath等多种解析方式

对spring的支持比较全面

Demo

1.引入maven依赖

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>3.0.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

2.编写Controller

@GetMapping("/add")
public Result add() {
    User user = new User();
     ......
    return Result.ok();
}

Service、Dao层省略

3.编写单元测试接口

首先编写一个基类,后续的单元测试类只需继承这个基类就可以了。

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseTest {

    @Autowired
    WebApplicationContext webApplicationContext;

    @LocalServerPort
    private int port;

    @BeforeEach
    public void commonSetUp() {
        RestAssured.port = port;
        RestAssured.requestSpecification = new RequestSpecBuilder()
                .setContentType(ContentType.JSON)
                .setAccept(ContentType.JSON)
                .build();
    }

}

Controller的单元测试


public class PersonControllerTest extends BaseTest {
    @Test
    public void test1() throws Exception {
        RestAssured.given()
                .get("/add")
                .then().log().all();
    }
}

结果如下:


{
    "code": 200,
    "msg": "操作成功",
    "data": null
}

说明:

given():一次网络请求所需要的条件都写在这里,头信息、query参数

get(): rest请求,还有delete()、put()、post()

when():触发条件

then():断言

log():打印日志

body():参数解析校验

更多请查看: testerhome.com/wiki/restas…

Demo测试:以创建商品信息的品牌为例如下:

public class BrandControllerTest extends BaseTest {

/**
 * description:单元测试:新增品牌
 */
@Test
@Transactional
public void creatBrandTest() {
    //新增品牌定义入参
    BrandInfoParam param = new BrandInfoParam();
    param.setLevel(7);
    param.setAlisaName("xix");
    param.setName("娃嘻嘻");
    param.setLogo("testLogo");
    param.setStatus(1);
    param.setRemark("测试生成娃嘻嘻品牌");
    //设置请求参数
    RestAssured.given()
        .body(param)
        //日志打印
        .log().all()
        .when()
        //请求地址 post请求              
        .post("/brand")
        .then()
        //返回数据json解析
        .body("isSuccess", equalTo(true))
        .body("isError", equalTo(false))
        //打印全部日志
        .log().all();
}

/**
 * description:单元测试:更新品牌
 */
 
@Test
@Transactional
public void updateBrandByIdTest() {
    //更新品牌入参
    BrandInfoParam param = new BrandInfoParam();
    param.setLevel(7);
    param.setAlisaName("BigPeople");
    param.setName("大大众");
    param.setLogo("testLogo");
    param.setStatus(1);
    param.setRemark("测试更新大众品牌");
    //设置请求参数
    RestAssured.given()
        .pathParam("brandId", 10)
        .body(param)
        //日志打印
        .log().all()
        .when()
        //put请求
        .put("/brand/{brandId}")
        .then()
        //返回数据解析
        .body("isSuccess", equalTo(true))
        .body("isError", equalTo(false))
        .log().all();
}

/**
 * description:单元测试:删除品牌
 */
@Test
@Transactional
public void deleteBrandByIdTest() {
    //删除品牌
    //设置请求参数
    RestAssured.given()
        //路径参数@PathVariable
        .pathParam("brandId", 13)
        //日志打印
        .log().all()
        .when()
        //请求地址 delete请求
        .delete("/brand/{brandId}")
        .then()
        .body("code", equalTo(1))
        .body("isSuccess", equalTo(true))
        .body("isError", equalTo(false))
        .log().all();
}

/**
 * description:单元测试:查询列表
 */
@Test
@Transactional
public void getBrandListTest() {
    RestAssured.given()
        //参数
        .param("name", "米")
        .param("size", 10)
        .param("current", 1)
        .log().all()
        .when()
        //get请求
        .get("/brand")
        .then()
        //返回参数校验
        .body("isSuccess", equalTo(true))
        .body("isError", equalTo(false))
        .body("data.current", equalTo(1))
        .body("data.records.name", everyItem(matchesRegex("^(.*米.*)$")))
        .log().all();

}
 

更多请参阅:github.com/RookieTeste…