Callback
Mockito 提供了一个 Answer 接口,它允许使用通用接口进行stubbing。
语法
//add the behavior to add numbers
when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() {
@Override
public Double answer(InvocationOnMock invocation) throws Throwable {
//get the arguments passed to mock
Object[] args = invocation.getArguments();
//get the mock
Object mock = invocation.getMock();
//return the result
return 30.0;
}
});
举一个使用的例子:
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
private MathApplication mathApplication;
private CalculatorService calcService;
@Before
public void setUp(){
mathApplication = new MathApplication();
calcService = mock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAdd(){
//add the behavior to add numbers
when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() {
@Override
public Double answer(InvocationOnMock invocation) throws Throwable {
//get the arguments passed to mock
Object[] args = invocation.getArguments();
//get the mock
Object mock = invocation.getMock();
//return the result
return 30.0;
}
});
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
}
}
我们通过在其中注入一个calculatorService 的模拟来测试MathApplication 类。 Mock 将由 Mockito 创建。我们通过回调来实现一个接口来模拟方法的返回。
Spy
Mockito 提供了在真实对象上创建间谍的选项。当调用 spy 时,会调用真实对象的实际方法。
语法:
//create a spy on actual object
calcService = spy(calculator);
//perform operation on real object
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
还是用一个例子来说明:
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class MathApplicationTester {
private MathApplication mathApplication;
private CalculatorService calcService;
@Before
public void setUp(){
mathApplication = new MathApplication();
Calculator calculator = new Calculator();
calcService = spy(calculator);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAdd(){
//perform operation on real object
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
}
class Calculator implements CalculatorService {
@Override
public double add(double input1, double input2) {
return input1 + input2;
}
@Override
public double subtract(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
@Override
public double multiply(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
@Override
public double divide(double input1, double input2) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
}
}
看过代码后很容易理解,mock一般是对一个接口,而spy是对一个对象实例;这里提出一个问题,它们之间有什么区别呢?