JUnit 5 测试 class 属性在每次测试前都为空

JUnit 5 test class attributes are null before each test

我有一个带有非静态字符串属性 (value) 的 JUnit 5 测试 class。
测试 class 有 2 个测试方法,它们按定义的顺序执行(对于问题顺序无关紧要)。
第一个执行的测试方法将 String 属性设置为“Test”。
但是当执行第二个测试方法时,String 属性是 null 而不是“Test”。

为什么在 JUnit 5 中会这样?
除了将 String 属性设为静态之外,我可以用另一种方式处理吗?

下面是一些示例代码:

@TestMethodOrder(OrderAnnotation.class)
class Junit5Test {
  private String value;

  @Test
  @Order(1)
  void setValueTest() {
    this.value = "Test";
    assertNotNull(this.value);
  }

  @Test
  @Order(2)
  void readValueTest() {
    // This test fails, because value is null. Why?
    assertNotNull(this.value);
  } 
}

对于每个测试方法,都会创建一个新的测试实例 class,因此在调用之间不会保留状态更改,与测试方法的顺序无关。

Does Junit reinitialize the class with each test method invocation?

至于“以另一种方式处理”,我建议不要这样做。单元测试应该是独立的。

Tests should not depend on each other. One test should not set up the conditions for the next test. You should be able to run each test independently and run the tests in any order you like. When tests depend on each other, then the first one to fail causes a cascade of downstream failures, making diagnosis difficult and hiding downstream defects.

Robert C. Martin 简洁代码:敏捷软件工艺手册,第 9 章