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

查看:1220
本文介绍了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

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

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