Java单元测试给出NullPointer异常

时间:2018-11-08 07:27:52

标签: spring-boot junit mockito

我有一个单元测试引发NullPointer异常 当我将测试放在另一个文件中时,它运行良好 下面是一段代码。同一文件中的其他测试正在运行,没有任何错误。

@Test
public void validateShouldFailIfThereExistsABillingCycleWithSameId() {
    final String expectedErrorMessage = "Billing Cycle with id  " + id + " already exists";

    when(billingCycleServiceAuditable.
            findBillingCycleById(id, locale, DefaultAuth.SYSTEM_USER_NAME.getValue())).
            thenReturn(Optional.of(billingCycle));

    when(messageService.getMessage(I18Code.MESSAGE_CHARGING_BILLING_CYCLE_EXISTS.getCode(),
            new String[]{id.toString()}, locale)).thenReturn(expectedErrorMessage);
    when(mapper.map(billingCycle)).thenReturn(billingCycleDto);
    when(mapper.map(billingCycleDto)).thenReturn(billingCycle);

    final CommonResponse response = billingCycleValidator.validate(billingCycle, userAction, locale, DefaultAuth.SYSTEM_USER_NAME.getValue());
    assertNotNull(response);
    assertEq    @Test
public void validateShouldFailIfThereExistsABillingCycleWithSameId() {
    final String expectedErrorMessage = "Billing Cycle with id  " + id + " already exists";

    when(billingCycleServiceAuditable.
            findBillingCycleById(id, locale, DefaultAuth.SYSTEM_USER_NAME.getValue())).
            thenReturn(Optional.of(billingCycle));

    when(messageService.getMessage(I18Code.MESSAGE_CHARGING_BILLING_CYCLE_EXISTS.getCode(),
            new String[]{id.toString()}, locale)).thenReturn(expectedErrorMessage);
    when(mapper.map(billingCycle)).thenReturn(billingCycleDto);
    when(mapper.map(billingCycleDto)).thenReturn(billingCycle);

    final CommonResponse response = billingCycleValidator.validate(billingCycle, userAction, locale, DefaultAuth.SYSTEM_USER_NAME.getValue());
    assertNotNull(response);
    assertEquals(expectedErrorMessage, response.getNarrative());

    verify(billingCycleServiceAuditable,
            times(1))
            .findBillingCycleById(anyLong(), any(Locale.class), anyString());
}uals(expectedErrorMessage, response.getNarrative());

    verify(billingCycleServiceAuditable,
            times(1))
            .findBillingCycleById(anyLong(), any(Locale.class), anyString());
}

1 个答案:

答案 0 :(得分:1)

在测试课程的开头,请确保该课程用testrunner标注为波纹管

@RunWith(MockitoJUnitRunner.class)
public class BillingCycleValidatorImplCreateBillingCycleActionTest {
}