spring-boot - Java 单元测试给出 NullPointer 异常

标签 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());
}

最佳答案

在你的测试类开始时,确保类被注释为 testrunner 如下所示

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

关于spring-boot - Java 单元测试给出 NullPointer 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53203103/

相关文章:

java - 是mockito使用反射api来模拟对象

android - 为什么我的单元测试针对的是错误版本的Android?

spring - 如何在后期初始化中保留不可为空的属性

java - Spring Error Controller 响应 Not Acceptable

java - jUnit:NPE 关于私有(private)成员初始化

java - 使用模拟验证错误消息,其中结果可以根据 id 更改

java - Spring Boot项目中在多个数据库中执行搜索操作

java - java.lang.OutOfMemoryError : unable to create new native thread error using ChromeDriver and Chrome through Selenium in Spring boot

java - org.mockito.Mockito.times(1) 有方便的方法吗?

unit-testing - 基于Consumer功能接口(interface)的单元测试回调