Junit5学习笔记

pom.xml依赖

<?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>

    <groupId>com.ceshiren</groupId>
    <artifactId>junit-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <maven.compiler.version>3.10.1</maven.compiler.version>
        <maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
        <!-- 使用 Java 11 语言特性 ( -source 11 ) 并且还希望编译后的类与 JVM 11 ( -target 11 )兼容,
        可以添加以下两个属性,它们是默认属性插件参数的名称 -->
        <java.version>11</java.version>
        <!-- 对应junit Jupiter的版本号;放在这里就不需要在每个依赖里面写版本号,导致对应版本号会冲突 -->
        <junit.jupiter.version>5.9.1</junit.jupiter.version>
        <!-- log日志 -->
        <slf4j.version>2.0.3</slf4j.version>
        <logback.version>1.4.3</logback.version>
        <!-- allure报告 -->
        <allure.version>2.19.0</allure.version>
        <jackson.version>2.15.0</jackson.version>
        <aspectj.version>1.9.9.1</aspectj.version>
        <allure.maven.version>2.11.2</allure.maven.version>
        <allure.cmd.download.url>
            https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline
        </allure.cmd.download.url>
    </properties>
    <!--    物料清单 (BOM)-->
    <dependencyManagement>
        <dependencies>
            <!--当使用 Gradle 或 Maven 引用多个 JUnit 工件时,此物料清单 POM 可用于简化依赖项管理。不再需要在添加依赖时设置版本-->
            <dependency>
                <groupId>org.junit</groupId>
                <artifactId>junit-bom</artifactId>
                <version>${junit.jupiter.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- junit5 -->
        <!-- 创建 Junit5 测试用例的 API-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <!--对应添加的依赖的作用范围-->
            <scope>test</scope>
        </dependency>
        <!-- 兼容 JUnit4 版本的测试用例-->
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <!--suite套件依赖 -->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-suite</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- log日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>compile</scope>
        </dependency>

        <!--        allure报告-->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-junit5</artifactId>
            <version>${allure.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <!-- 设置jre版本为 11 -->
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <!-- 设置编码为 UTF-8 -->
                    <encoding>${maven.compiler.encoding}</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    </argLine>
                    <includes>
                        <include>**/*Test</include>
                        <include>**/Test*</include>
                    </includes>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>${allure.maven.version}</version>
                <configuration>
                    <reportVersion>${allure.version}</reportVersion>
                    <allureDownloadUrl>${allure.cmd.download.url}/${allure.version}/allure-commandline-${allure.version}.zip</allureDownloadUrl>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

@Test注解:标注用例

@DisplayName注解:用例执行名称

package com.ceshiren.demo;
import org.junit.jupiter.api.Test;

public class JunitTest {
    @Test
    @DisplayName("测试用例1")
    public void OneTest(){
        System.out.println("1111");
    }
}

@BeforeAll:每个类开始执行一次,需要用static修饰

@AfterAll:每个类结束执行一次,需要用static修饰

@BeforeEach:每个方法开始执行一次

@AfterEach:每个方法结束执行一次

package com.ceshiren.demo;
import org.junit.jupiter.api.*;
public class SonTest extends FatherTest {
    @BeforeAll
    static void setUpClass(){
        System.out.println("子类setUpClass");
    }
    @AfterAll
    static void tearDownClass(){
        System.out.println("子类tearDownClass");
    }
    @BeforeEach
    void setUp(){
        System.out.println("子类setUp");
    }
    @AfterEach
    void tearDown(){
        System.out.println("子类tearDown");
    }
    @Test
    void one(){
        System.out.println("子类111");
    }
    @Test
    void two(){
        System.out.println("子类222");
    }
}

常用断言:

assertEqual、assertThat、assertTrue、assertAll(多断言)

		assertEquals(2,1+1);
        assertThat("Ab",is("Ab"));
        assertTrue("abc".contains("a"));
        //多断言
        assertAll(
                ()->{assertEquals(2,1+1);},
                ()->{assertEquals(2,1+1);}
        );

参数化用例:

@ParameterizedTest(name = “{0}+{1}={2}”)

@MethodSource

package com.ceshiren;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.io.File;
import java.io.IOException;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;

@DisplayName("测试计算器")
public class CalculatorTest extends BaseTest{
    @ParameterizedTest(name = "{0}+{1}={2}")
    @MethodSource
    @DisplayName("加法正向测试111")
    public void sum(int a,int b,int re){
        result = calculator.sum(a,b);
        assertEquals(re,result,"计算结果错误");
    }
    public static Stream<Arguments> sum(){
        return Stream.of(
                Arguments.arguments(2,2,4),
                Arguments.arguments(4,5,9),
                Arguments.arguments(8,3,11)
        );
    }
  }

@Order注解:用例排序

  • resources目录下创建文件junit-platform.properties
  • junit.jupiter.testmethod.order.default = org.junit.jupiter.api.MethodOrderer$OrderAnnotation
  • 使用注解@Order(1)
	@Order(3)
    public void sum(int a,int b,int re){
        result = calculator.sum(a,b);
        assertEquals(re,result,"计算结果错误");
    }

@tag注解:设置标签

	@Tag("dev")
    @Tag("pre")
    @Test
    void SixTest(){
        System.out.println("测试666");
    }

@Disabled注解:禁止执行

 @Test
    @Disabled("禁止方法执行")
    void OneTest(){
        System.out.println("禁止 - 测试用例1");
    }

TestInfo参数:在beforeEach和afterEach中可回调获取当前用例信息

回调获取用例DisplayName

	@BeforeEach
    public void BeforeEach(TestInfo testInfo){
        String sub = "";
        String displayName = testInfo.getDisplayName();
        if(displayName.contains("加法")){
            sub = "加法";
        }else if(displayName.contains("减法")){
            sub = "减法";
        }else if(displayName.contains("字符串")) {
            sub = "字符串";
        }
        System.out.println("BeforeEach ---> 运行"+sub+"运算");
        logger.info("开始计算");
    }

回调获取用例方法名称

	@AfterEach
    public void AfterEach(TestInfo testInfo){
        String sub = "";
        Optional<Method> testMethod = testInfo.getTestMethod();
        Optional<String> s = testMethod.map(Method::getName);
        if(s.filter(str -> str.contains("sum")).isPresent()){
            sub = "加法";
        }
        else if(s.filter(str -> str.contains("sub")).isPresent()){
            sub = "减法";
        }
        else{
            sub = "字符串";
        }
        System.out.println("AfterEach ---> "+sub+"运算");
        logger.info("计算结果为{}",result);
    }

读取YAML文件数据

yaml数据

datas:
  - a: 1
    b: 1
    result: 2
    message: 有效2个整数【1,1】
  - a: 98
    b: 98
    result: 196
    message: 有效边界值相加【98,98】
  - a: -98
    b: 98
    result: 0
    message: 有效边界值相加【-98,98】
  - a: 98
    b: -98
    result: 0
    message: 有效边界值相加【98,-98】
  - a: -98
    b: -98
    result: -196
    message: 有效边界值相加【-98,-98】
  - a: 100
    b: 0
    result: 0
    message: 无效边界值相加【100,0】
  - a: -100
    b: -1
    result: 0
    message: 无效边界值相加【-100,-1】
  - a: 2
    b: 100
    result: 0
    message: 无效边界值相加【2,100】
  - a: 1
    b: -100
    result: 0
    message: 无效边界值相加【1,-100】

封装类Adata

package com.ceshiren.entity;

public class Adata {
    private int a;
    private int b;
    private int result;
    private String message;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Adata(int a, int b, int result, String message) {
        this.a = a;
        this.b = b;
        this.result = result;
        this.message = message;
    }

    public Adata() {
    }

    @Override
    public String toString() {
        return "Adata{" +
                "a=" + a +
                ", b=" + b +
                ", result=" + result +
                ", message='" + message + '\'' +
                '}';
    }
}

封装Adata的集合类

package com.ceshiren.entity;

import java.util.List;

public class Data {
    private List<Adata> datas;

    public List<Adata> getDatas() {
        return datas;
    }

    public void setDatas(List<Adata> datas) {
        this.datas = datas;
    }

    @Override
    public String toString() {
        return "Data{" +
                "datas=" + datas +
                '}';
    }

    public Data(List<Adata> datas) {
        this.datas = datas;
    }

    public Data() {
    }
}

实现获取yaml数据

@ParameterizedTest
    @MethodSource
    public void YamlTest2(Adata adata) {
        System.out.println(adata.getA());
        System.out.println(adata.getB());
        System.out.println(adata.getResult());
        System.out.println(adata.getMessage());
    }

    public static Stream<Adata> YamlTest2() throws IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.findAndRegisterModules();
        Data data;
        TypeReference<Data> typeReference = new TypeReference<>() {};
        data = mapper.readValue(new File("src/test/resources/data.yaml"),typeReference);
        return data.getDatas().stream();
    }

动态测试用例

package com.ceshiren;

import com.ceshiren.entity.Data;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.w3c.dom.ls.LSOutput;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

public class ShellTest {
    Data data;

    private void getYaml() throws IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.findAndRegisterModules();
        TypeReference<Data> typeReference = new TypeReference<>() {};
        data = mapper.readValue(new File("src/test/resources/data.yaml"),typeReference);
    }

    @TestFactory
    Collection<DynamicTest> shellDyList() throws IOException {
        Collection<DynamicTest> shellDyList = new ArrayList<>();
        getYaml();
        System.out.println(data);
        data.getDatas().forEach(
                shellResult -> {
                    DynamicTest test = DynamicTest.dynamicTest("name",
                            () -> {
                                System.out.println("a:" + shellResult.getA());
                                System.out.println("b:" + shellResult.getB());
                                System.out.println("result:" + shellResult.getResult());
                                System.out.println("message:" + shellResult.getMessage());
                            }
                    );
                    shellDyList.add(test);
                }
        );
        return shellDyList;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值