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

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

问题描述

目前,我正在阅读JUnit in action"一书.在这本书中,我发现了以下文字:

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

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.

因此,通常不鼓励在测试中使用静态变量,因为它会破坏每个测试一个实例的整个目的,即为每个测试提供一个干净的石板.

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天全站免登陆