英文:
Junit BeforeAll or BeforeEach - when to initialise class under test if state does not change between tests?
问题
在我的下面的示例中,我不确定是否应该使用BeforeEach
还是BeforeAll
- 请注意,在测试的类Calculator
之间不会改变状态等,因此我认为将其设置为static
并使用BeforeEach
更高效?
public class CalculatorShould {
private static Calculator calculator;
@BeforeAll
static void setUp() {
calculator= new Calculator();
}
@Test
void calculatePriceForTwo() {
// act
Double price = calculator.calculatePrice(2);
// assert
assertEquals(10, price);
}
@Test
void calculatePriceForFour() {
// act
Double price = calculator.calculatePrice(4);
// assert
assertEquals(20, price);
}
}
英文:
In my following example I am unsure if I should use BeforeEach
or BeforeAll
- Note the class under test Calculator
does not change state etc between tests so I assumed making it static
and using BeforeEach
is more efficient?
public class CalculatorShould {
private static Calculator calculator;
@BeforeAll
static void setUp() {
calculator= new Calculator();
}
@Test
void calculatePriceForTwo() {
// act
Double price = calculator.calculatePrice(2);
// assert
assertEquals(10, price);
}
@Test
void calculatePriceForFour() {
// act
Double price = calculator.calculatePrice(4);
// assert
assertEquals(20, price);
}
}
答案1
得分: 2
在你的示例中,我认为你不需要BeforeAll
或BeforeEach
。
相反,更简单(代码更简洁)的方式是只需声明:
public class CalculatorShould {
private Calculator calculator = new Calculator();
// 测试方法不变...
}
JUnit会在每次运行测试方法之前为你提供一个全新的Calculator
实例:
为了允许单独执行测试方法并避免可变测试实例状态导致意外副作用,JUnit会在执行每个测试方法之前为每个测试类创建一个新实例(参见测试类和方法)。这种“每方法”测试实例生命周期是JUnit Jupiter的默认行为,与所有以前的JUnit版本类似。
来源:https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle
英文:
I think in your example you don't need either BeforeAll
or BeforeEach
.
Instead, it's simpler (less code is good) to just declare:
public class CalculatorShould {
private Calculator calculator = new Calculator();
// test methods unchanged...
}
JUnit will provide you with a brand new instance of the Calculator
before each test method is run:
> In order to allow individual test methods to be executed in isolation and to avoid unexpected side effects due to mutable test instance state, JUnit creates a new instance of each test class before executing each test method (see Test Classes and Methods). This "per-method" test instance lifecycle is the default behavior in JUnit Jupiter and is analogous to all previous versions of JUnit.
Source: https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-instance-lifecycle
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论