【问题标题】:Java Unit Tests giving NullPointer ExceptionJava 单元测试给出 NullPointer 异常
【发布时间】:2019-04-11 16:30:33
【问题描述】:

我有一个单元测试抛出 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());
}

【问题讨论】:

  • 包括堆栈跟踪

标签: spring-boot junit mockito


【解决方案1】:

在您的测试课程开始时,请确保该课程使用testrunner 注释,如下所示

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

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多