如何从 junit5 中的内部嵌套测试访问父变量

how to access a parent variable from a inner nested test in junit5

public class A{
   public String foo = null;

   @Test
   void assignValueToFoo(){
       foo = "foo";
   }

  @Nested
  class B{
     @BeforeEach
     void doSomethingBeforeEachTest(){
         assertNotNull(foo);
     }
  }
}

我需要访问 class B 中的 foo 变量而不使用 class A 中的 @BeforeEach,如何获取 class B 中变量 foo 的值?

您所描述的是预期的行为。

如果您不想在 A@BeforeEach 方法中执行 foo 字段的赋值,您唯一的选择是注释 A @TestInstance(Lifecycle.PER_CLASS) 以便在 B.

中执行测试时重用 A 的实例