如何在Spring Boot中使用TestNG
2020-08-23 本文已影响0人
狄仁杰666
前言
Java语言体系下,单元测试是Junit的天下,在Spring Boot框架中,Spring Boot Test也已经很好地集成了Junit测试框架。
想了解如何在Spring Boot框架下入手Junit,请看:
当测试组织方式越来越复杂,需要使用更灵活的测试框架时,如API/UI自动化测试场景,另一个广泛使用且优秀的选择是:
-
TestNG
如果我们想在Spring Boot使用TestNG测试框架,又该如何做呢?
整体步骤
- 添加TestNG依赖;
- 编写TestNG测试类;
- 运行测试类;
1. 添加TestNG依赖
在项目pom.xml文件内的dependencies节点添加TestNG依赖如:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.0.0</version>
<scope>test</scope>
</dependency>
2. 编写TestNG测试类;
特别注意几行代码:
- @SpringBootTest
- public class PostmanEchoTest extends AbstractTestNGSpringContextTests {...
package com.github.dylanz666.DemoTest;
import com.alibaba.fastjson.JSONObject;
import com.github.dylanz666.constant.MethodEnum;
import com.github.dylanz666.controller.RequestController;
import com.github.dylanz666.domain.RequestSpec;
import com.github.dylanz666.util.AssertUtil;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
/**
* @author : dylanz
* @since : 08/21/2020
**/
@SpringBootTest
@Feature("API in PostmanEchoTest")
public class PostmanEchoTest extends AbstractTestNGSpringContextTests {
@Autowired
private RequestController requestController;
@Autowired
private AssertUtil assertUtil;
@Test(priority = 1)
@Description("Get https://postman-echo.com/get?name=%s")
public void getPostmanEcho() throws Exception {
String name = "test1";
String url = "https://postman-echo.com/get?name=%s";
url = String.format(url, name);
RequestSpec requestSpec = new RequestSpec();
requestSpec.setUrl(url);
requestSpec.setMethod(MethodEnum.GET);
Response response = requestController.launch(requestSpec);
assertUtil.assertEquals(response.getStatusCode(), 200);
assertUtil.assertEquals(JSONObject.parseObject(response.asString()).getString("url"), url);
assertUtil.assertEquals(JSONObject.parseObject(response.asString()).getJSONObject("args").getString("name"), name);
}
}
3. 运行测试类;
1). IDEA直接启动测试类;

2). 命令行执行;
mvn clean test
就这么简单,跟在非Spring Boot项目中使用一样,TestNG的其他使用也一样,如TestNG配置文件的使用等,唯一的差别就是测试类要使用:
- @SpringBootTest
- public class PostmanEchoTest extends AbstractTestNGSpringContextTests {...
如此简单,动动手指点点赞?
谢谢!