Junit 是否会在每次调用测试方法时重新初始化类? [英] Does Junit reinitialize the class with each test method invocation?

查看:23
本文介绍了Junit 是否会在每次调用测试方法时重新初始化类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,两个测试用例都成立:

When i run the below code, both test cases come true:

import static junit.framework.Assert.assertEquals;

import org.junit.Test;

public class MyTest{
    private int count;

    @Before
    public void before(){
        count=1;
    }

    @Test
    public void test1(){
        count++;
        assertEquals(2, count); 
    }

    @Test
    public void test2(){
        count++;
        assertEquals(2, count); 
    }
}

预期行为

  1. test1 - 成功
  2. test2 - 失败(正如预期的那样计数将变为 3)

实际行为

  1. test1 - 成功
  2. test2 - 成功

为什么 junit 在每次调用测试方法时重新初始化类/变量.这是junit中的一个错误或故意提供的.

Why junit is reinitializing class/variable with each test method invocation. It is a bug in junit or is provided intentionally.

推荐答案

每个测试的 MyTest 的新实例方法

对于每个测试方法,将创建 MyTest 的一个新实例,这是 Junit 的行为.

New Instance of MyTest for each test method

For each test method a new instance of MyTest will be created this is the behavior of Junit.

因此,在您的情况下,对于这两种方法,变量 count 的值为 1,因此 count++ 的值为 2 测试方法和测试用例都通过了.

So in your case for both methods the variable count will have value 1, and thus the value of count++ will be 2 for both the test methods and hence the test cases pass.

public class MyTest{
   public MyTest(){
      // called n times
      System.out.println("Constructor called for MyTest");
   }

   @Before //called n times
   public void setUp(){
      System.out.println("Before called for MyTest");
   }
    
   //n test methods
}

如果您使用 2 个测试方法执行上面的代码:

If you execute the code above with 2 test methods:

输出将是:

Constructor called for MyTest
Before called for MyTest
//test execution
Constructor called for MyTest
Before called for MyTest

测试框架可帮助您做正确的事情,单元测试的一个非常重要的特性是隔离.

Test frameworks help you in doing the right thing, a very important property of unit tests is isolation.

通过为每个测试方法创建一个新实例,脏的 SUT 被丢弃.这样我们每次测试都有一个新鲜的状态.

By creating a new instance every test method, the dirty SUT is thrown away. So that we have a fresh state for every test.

阅读 F.I.R.S.T 测试原理.

Read about F.I.R.S.T principle of testing.

这篇关于Junit 是否会在每次调用测试方法时重新初始化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆