【发布时间】:2017-07-10 12:05:48
【问题描述】:
我是 Spring、Maven 和单元测试 (TDD) 的新手,我必须在新项目中同时使用所有 3 个。
过去一天我一直在阅读教程和代码示例,但找不到解决方案。
对于这个例子(一个计算器),假设我有以下接口:
public interface CalculatorService {
public double add(double input1,
double input2);
public double substract(double input1,
double input2);
}
这是接口的实现,依赖注入风格:
public class MathApplication {
private CalculatorService calcService;
public void setCalcService(final CalculatorService calcService) {
this.calcService = calcService;
}
public double add(final double input1,
final double input2) {
return this.calcService.add(input1, input2);
}
public double substract(final double input1,
final double input2) {
return this.calcService.substract(input1, input2);
}
}
测试类:
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
@Rule
public final ExpectedException exception = ExpectedException.none();
@InjectMocks // Marks where to inject the mocks.
MathApplication mathApplication = new MathApplication();
@Mock // Marks the mocks to be injected.
CalculatorService calcService;
@Test
public void whenAddCorrectThenDoOperation() {
// GIVEN
// WHEN
when(this.calcService.add(10.0, 20.0)).thenReturn(30.00); // Adds the behaviour of calc service
// to add two numbers.
// THEN
assertThat(this.mathApplication.add(10.0, 20.0)).isEqualTo(30.0); // Tests the functionality
// added.
verify(calcService, times(1)).add(10.0, 20.0);
}
@Test
public void whenSubstractIsCorrectThenDoOperation() throws Exception {
// GIVEN
// WHEN
when(calcService.substract(20.0, 8.0)).thenReturn(12.0);
// THEN
assertThat(mathApplication.substract(20.0, 8.0)).isEqualTo(12.0);
}
}
这是主要的,就像我现在拥有的那样:
@SpringBootApplication
public class TddMockitoApplication {
public static void main(String[] args) {
SpringApplication.run(TddMockitoApplication.class, args);
}
}
我的问题是:如果我想进行加法或减法,我必须在 main 中添加什么,或者如何运行此代码。
【问题讨论】:
标签: java spring maven unit-testing dependency-injection