junit_demo
参考:JUnit5单元测试框架的使用教程与简单实例_junit5使用_pan_junbiao的博客-CSDN博客
Junit单元测试例子demo_twentyfour4ever的博客-CSDN博客
目录结构

pom.xml
<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>org.example</groupId>
  <artifactId>junit_demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>junit_demo</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
被测试类
package com.hmb;
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    public int sub(int a, int b) {
        return a - b;
    }
}
测试类
package com.hmb;
import junit.framework.Assert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
class CalculatorTest {
    static Calculator calculator;
    static int testNo = 0;
    @BeforeAll
    static void beforeAll() {
        System.out.println("test start...");
        calculator = new Calculator();
    }
    @AfterAll
    static void AfterAll() {
        System.out.println("test end...");
    }
    @org.junit.jupiter.api.BeforeEach
    void setUp() {
        System.out.println("start test NO. " + testNo);
    }
    @AfterEach
    void tearDown() {
        System.out.println("end test NO. " + testNo++);
    }
    @org.junit.jupiter.api.Test
    void add() {
        int result = calculator.add(1, 2);
        Assert.assertEquals(3, result);
    }
    @org.junit.jupiter.api.Test
    void sub() {
        int result = calculator.sub(2, 1);
        Assert.assertEquals(1, result);
    }
}
运行结果:
点击测试类名左边的运行按钮,就会运行所有此类测试用例

 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号