public class Calculator {
public int subtract(int a, int b) {
return a - b;
}
并为其创建了测试:
代码语言:
javascript
复制
import lombok.AllArgsConstructor;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@AllArgsConstructor
class CalculatorTest {
private final Calculator calculator;
private static final int SUBTRACTION_RESULT = 2;
@Test
void subtractTest() {
int result = calculator.subtract(5, 3);
assertEquals(result, SUBTRACTION_RESULT);
}
测试失败:
代码语言:
javascript
复制
org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [final com.udemy.junits.Calculator calculator] in constructor [public com.udemy.junits.CalculatorTest(com.udemy.junits.Calculator)].
据我所知,它无法初始化和实例化计算器。在没有Lombok的情况下,我尝试这样做,并添加了构造函数:
代码语言:
javascript
复制
public CalculatorTest(Calculator calculator) {
this.calculator = calculator;
}
结果是一样的。然后,我使用@BeforeAll以这种方式实例化了这个示例:
代码语言:
javascript
复制
@BeforeAll
static void init() {
calculator = new Calculator();
}
这个成功了。这里没有依赖注入,因为我们没有应用程序上下文吗?还是我搞错了?如果不将计算器var实例化为
new Calculator()
,就可以在这里执行依赖注入吗?
public class Calculator {
public int subtract(int a, int b) {
return a - b;
@RequiredArgsConstructor
@RunWith(Parameterized.class)
class CalculatorTest {
private final int x;
private final int y;
private final int z;
private Calculator calculator;
// Constructor is generated by lombok with @RequiredArgsConstructor
// and accepts three parameters, x, y, and z
@BeforeEach
void setUp() {
calculator = new Calculator();
@Test
void testSubtract() {
assertEquals(z, calculator.subtract(x, y));
* This method will pass each parameter into the constructor
* of this test class. In this case, the testSubtract method
* will be ran 4 times with each set of parameters.
@Parameterized.Parameters
static Collection parameters() {
return Arrays.asList(
new Object[][] {
{5, 3, 2},
{10, 1, 9},