如何在Spring Boot中使用TestNG

前言

Java語言體系下,單元測試是Junit的天下,在Spring Boot框架中,Spring Boot Test也已經很好地集成了Junit測試框架。
想了解如何在Spring Boot框架下入手Junit,請看:

當測試組織方式越來越復雜,需要使用更靈活的測試框架時,如API/UI自動化測試場景,另一個廣泛使用且優秀的選擇是:

  • TestNG

如果我們想在Spring Boot使用TestNG測試框架,又該如何做呢?

整體步驟

  1. 添加TestNG依賴;
  2. 編寫TestNG測試類;
  3. 運行測試類;

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直接啟動測試類;

IDEA直接啟動

2). 命令行執行;

mvn clean test

就這么簡單,跟在非Spring Boot項目中使用一樣,TestNG的其他使用也一樣,如TestNG配置文件的使用等,唯一的差別就是測試類要使用:

  • @SpringBootTest
  • public class PostmanEchoTest extends AbstractTestNGSpringContextTests {...

如此簡單,動動手指點點贊?

謝謝!

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。