Skip to content

测试

单元测试

Junit

  • 在项目引入

    //Maven
    <dependency>
        <groupId> junit </groupId>
        <artifactId> junit </artifactId>
        <version> 5.7.0 </version>
        <scope> test </scope>
    </dependency>
    

  • 使用(Maven Surefire 插件)执行mvn test

  • 测试用例
  • @Test标记测试方法(会被自动执行)
  • 使用断言(如 assertEquals)来验证预期结果与实际结果是否一致。

    public class Calculator {
        public int add(int a, int b) {
            return a + b;
        }
    }
    
    import static org.junit.Assert.assertEquals;
    import org.junit.Test;
    
    public class CalculatorTest {
    
        @Test
        public void testAdd() {
            Calculator calculator = new Calculator();
            int result = calculator.add(5, 3);
            assertEquals(8, result);
        }
    }
    

  • 生命周期注解

  • @BeforeAll@AQfterAll
  • @BeforeEach@AfterEach

前置条件

  • 断言
  • assert boolean-expression[: information-expression]
  • 可选字符串用于输出显示
  • 断言默认不会生效,需要在运行时添加-ea参数

    • 或者ClassLoader.getSystemClassLoader().setDefaultAssertionDtstatus(true);
  • Google Guava实现的断言

  • 提供始终启用的断言
    import com.google.common.base.*;
    import static com.google.common.base.Verify.*;
    verify(1 + 2 == 4);
    verify(1 + 2 == 4, "Bad math");
    verify(1 + 2 == 4, "Bad math: %s", "not 4");
    verifyNotNull(s);
    s = verifyNotNull(s);
    

契约式设计Dbc

  • 前置条件
  • 确保调用方法的代码符合要求
  • 后置条件
  • return语句之前,验证计算结果
  • 不变项
  • 对象在方法调用之间保持不变的状态

基准测试

  • 计算一段代码的运行时间

使用JMH微基准测试工具

  • maven导入

    <dependencies>
      <dependency>
        <groupId> org.openjdk.jmh </groupId>
        <artifactId> jmh-core </artifactId>
        <version> 1.33 </version> <!-- Use the latest version -->
      </dependency>
      <dependency>
        <groupId> org.openjdk.jmh </groupId>
        <artifactId> jmh-generator-annprocess </artifactId>
        <version> 1.33 </version> <!-- Use the latest version -->
      </dependency>
    </dependencies>
    

  • 注解

    //测试方法
    @Benchmark
    public void myTest() {
        // benchmarked code here
    }
    //测试前的初始化
    @Setup
    public void setup(){
    
    }
    //测试之后的清理
    @TearDown
    //基准测试的独立运行次数
    @Fork(1)
    //测试的线程数
    @Threads(Threads.MAX)
    //预热的迭代次数和时间
    @Warmup
    //实际测试的迭代次数和时间
    @Measurement
    //多组测试(值必须是字符串)
    @Param({
        "1",
        "10"
    })
    int size;
    

  • 预设

    @State(Scope.Thread)
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    @Warmup(iterations = 5)
    @Measurement(iterations = 5)
    @Fork(1)
    

补充

  • 样式检查(编码风格):Chgeckstyle
  • 静态错误分析:Findbugs