下面是我的测试代码:
@TestSubject
MathApplication mathApplication = new MathApplication();
@Mock
CalculatorService calculatorService;
@Test
public void testAdd() {
EasyMock.expect(calculatorService.add(10.0, 20.0)).andReturn(30.00);
Assert.assertEquals(30.0, mathApplication.add(10.0, 20.0), 0);
}
CalculatorService 是一个接口(interface),它定义了 add() 方法,该方法将在类 MathApplication 的 add() 方法中调用。 正如您所看到的,EasyMock.replay() 没有被调用,所以当我运行测试类时,结果显示为:
java.lang.AssertionError: Expected :30.0 Actual :0.0
令我困惑的是,既然没有实现CalculatorService,为什么没有抛出NullPointerException?
最佳答案
EasyMock 实现了 CalculatorService
,因为您已使用 @Mock 对它进行了注释,并且正在适当的 EasyMock TestRunner(或规则)中运行。但是,由于在断言时它仍处于记录模式,因此所有方法都是合法的,但它们会返回一些垃圾默认值,例如您的情况下的 0。
关于java - 为什么使用 EasyMock 时会抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32432588/