为什么在使用 EasyMock 时抛出 NullPointerException

Why is NullPointerException thrown while using EasyMock

下面是我的测试代码:

@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 是一个接口,它定义了 add() 方法,该方法将在 class MathApplication 的 add( ) 方法。 如您所见,未调用 EasyMock.replay(),因此当我 运行 测试 class 时,结果显示为:

java.lang.AssertionError: Expected :30.0 Actual :0.0

令我困惑的是,既然没有实现CalculatorService,为什么没有抛出NullPointerException?

EasyMock 实现了 CalculatorService,因为您已经用 @Mock 对其进行了注释并且 运行 在适当的 EasyMock TestRunner(或规则)中。但是,由于在您断言时它仍处于记录模式,因此所有方法都是合法的,但它们将 return 一些垃圾默认值,例如您的情况下的 0。