JUnit:在调用每个@Test方法之前的新实例。有什么好处? [英] JUnit: new instance before invoking each @Test method. What are the benefits?

查看:176
本文介绍了JUnit:在调用每个@Test方法之前的新实例。有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在阅读JUnit in action一书。在本书中,我找到了以下文本:

Currently, I am reading "JUnit in action" book. In this book I found text below:


在调用每个
@Test方法之前,JUnit会创建测试类的新实例。这有助于在测试方法之间提供独立性,并且
避免了测试代码中的无意的副作用。因为每个测试
方法都在一个新的测试类实例上运行,所以我们不能在测试方法中重用实例
变量值。

JUnit creates a new instance of the test class before invoking each @Test method. This helps provide independence between test methods and avoids unintentional side effects in the test code. Because each test method runs on a new test class instance, we can’t reuse instance variable values across test methods.

现在我认为这种方法没有多大意义:

Now I do not see much point in this approach:

例如:

public class CalculatorTest {
@Test
public void testAdd_1() {
Calculator calculator = new Calculator();
double result = calculator.add(1, 1);
assertEquals(2, result, 0);
}
@Test
public void testAdd_2() {
Calculator calculator = new Calculator();
double result = calculator.add(2, 2);
assertEquals(4, result, 0);
}

}

对于测试类CalculatorTest,没有任何好处。

For test class CalculatorTest there are no any benefits.

好的,让我们继续关注另一个例子:

Ok, lets go pay attention on another example:

public class OneTest {

    static byte count;

    public OneTest() {
        count++;
    }

    @Test
    public void test1() {
        System.out.println(count);
    }

    @Test
    public void test2() {
        System.out.println(count);
    }
}

对于测试类OneTest我找到了一种方法来使用许多测试方法的变量计数相同...

For test class OneTest I found a way to use the same variable count for the many test methods...

那么,如何看待书中描述的方法的真正好处?

so, How to see the real benefits of the approach described in the book?

推荐答案


如何看待本书所述方法的真正好处?

How to see the real benefits of the approach described in the book?

单独实例的目的不是为了任何好处,而是为了维护合同,即每个测试应该独立执行,而不会影响先前测试的执行。除了为每个测试使用不同的实例之外,没有其他方法可以确保此合同。

The purpose of separate instance is not for any benefit but to maintain the contract that each test should be independently executed without any effect of the execution of a previous test. There is just no other way to ensure this contract other than using a different instance for each test.

例如,Spring事务管理确保回滚对所做的所有更改默认情况下,数据库通过测试来维护相同的合同。

For example, the Spring transaction management makes sure to rollback all changes made to the database by a test, by default, to maintain the same contract.

因此,通常不鼓励在测试中使用静态变量,因为它会破坏一个目的的全部目的。 -exance-per-test为每个测试提供一个干净的平板。

So, using static variables in a test is generally discouraged as it will defeat the whole purpose of one-instance-per-test to have a clean slate for each test.

这篇关于JUnit:在调用每个@Test方法之前的新实例。有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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