我有一个单元测试抛出 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/