静态成员值被带到下一个测试

时间:2017-10-21 18:51:05

标签: java unit-testing testng

我正在对下面的课程进行单元测试

public class A {
 private static String aStr = null;

 public void doSomething() {
    if (null == aStr) {
       // do something to init aStr, and this initialized val gets cached for future calls.
       aStr = some_val;
    } else {
      // do something else using aStr value.
   }
 }

现在我正在进行单元测试:

public class ATest {
 private A a;

 @BeforeMethod
 public void setup() {
    a = new A();
 }

  @Test
  public void test1() {
    a.doSomething();
    // assert on some_val being fetched correctly.
  }

  @Test
  public void test2() {
    a.doSomething();
    // assert again for some_val

    // this is where some_val fetching is not invoked at all, while debugging I 
    // can see that aStr is already being initialized from previous test. 
  }
}

我假设因为我正在重新初始化对象' a'在@BeforeMethod设置中,我应该为所有测试得到空值。这个假设是否正确?

1 个答案:

答案 0 :(得分:2)

java中字段的

static修饰符表示此字段不属于该类的特定实例,而是属于类本身。在大多数情况下,您只能运行JVM中的类的示例。所以你创建这个类的对象并不重要 - 它们都将共享一个相同的静态字段。和该字段的一个相同值