目前,我正在阅读“JUnit in action”一书。在本书中,我找到了以下文字:
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.
现在我看不出这种方法有多大意义:
例如:
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 没有任何好处。
好吧,让我们关注另一个例子:
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,我找到了一种方法,可以为许多测试方法使用相同的变量计数...
那么,如何看出书中描述的方法的真正好处呢?
最佳答案
How to see the real benefits of the approach described in the book?
单独实例的目的不是为了任何好处,而是为了维护契约(Contract),即每个测试都应该独立执行,而不会影响先前测试的执行。除了为每个测试使用不同的实例之外,没有其他方法可以确保这种契约。
例如,Spring 事务管理确保回滚测试对数据库所做的所有更改,默认情况下,以维护相同的契约。
因此,通常不鼓励在测试中使用静态变量,因为它会破坏每个测试一个实例的整个目的,即为每个测试提供一个干净的平板。
关于java - JUnit:调用每个@Test 方法之前的新实例。有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010222/