mock when 无返回怎么办,Mockito.when()。thenReturn()不起作用或返回null

During the test there is a NullPointerException thrown. I tried to debug it and the only thing I worked out was that eventOptional is always null. Just as if Mockito.when().thenReturn() didn't work. Can anybody help? Here's my code for a tested service and for the test itself:

@Service

public class EventService {

@Autowired

public EventService(EventRepository eventRepository) {

this.eventRepository = eventRepository;

}

//...

public void updateEvent(EventDTO eventDTO) {

Optional eventOptional = eventRepository.findOneById(eventDTO.getId());

eventOptional.orElseThrow(() -> new BadRequestException(EVENT_NOT_FOUND));

//...

}

}

And the test class:

@RunWith(MockitoJUnitRunner.class)

public class EventServiceTest {

@Mock

private EventRepository eventRepository;

@InjectMocks

private EventService eventService;

private Event sampleEventFromDb;

@Before

public void setUp() throws Exception {

MockitoAnnotations.initMocks(this);

}

@Test

public void shouldUpdateEventTestAndWithProperTime() throws Exception {

EventDTO eventDTOMock = Mockito.mock(EventDTO.class);

sampleEventFromDb = Event.builder()

.name("name")

.startDateTime(LocalDateTime.now())

.placeName("place")

.description("description")

.publicEvent(true)

.owner(new User())

.build();

Mockito.when(eventRepository.findOneById(anyString())).thenReturn(Optional.of(sampleEventFromDb));

Mockito.when(eventDTOMock.getId()).thenReturn("1");

eventService.updateEvent(eventDTOMock); //NullPointerException

//...

}

}

解决方案

Looks like the problem is that initMock is called twice: once by the runner and once by the setUp method. Running the test with the regular runner or removing the initMocks call from the setUp method fixes this problem.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mockito 默认不支持模拟静态方法,但是可以使用第三方库 PowerMockito 来模拟静态方法。下面是一个例子: 假设有一个类 `StringUtil`,其中有一个静态方法 `isEmpty`,我们需要对其进行模拟: ``` public class StringUtil { public static boolean isEmpty(String str) { return str == null || str.isEmpty(); } } ``` 使用 PowerMockito 可以这样模拟: ``` @RunWith(PowerMockRunner.class) @PrepareForTest(StringUtil.class) public class StringUtilTest { @Test public void testIsEmpty() { PowerMockito.mockStatic(StringUtil.class); // mock 静态方法 Mockito.when(StringUtil.isEmpty(Mockito.anyString())).thenReturn(true); // 模拟静态方法的行为 Assert.assertTrue(StringUtil.isEmpty(null)); Assert.assertTrue(StringUtil.isEmpty("")); Assert.assertTrue(StringUtil.isEmpty(" ")); Assert.assertFalse(StringUtil.isEmpty("abc")); } } ``` 在上面的代码中,我们使用了 `@RunWith(PowerMockRunner.class)` 和 `@PrepareForTest(StringUtil.class)` 来启用 PowerMockito 的静态方法模拟功能,并指定要模拟的类。然后使用 `PowerMockito.mockStatic(StringUtil.class)` 来 mock 静态方法,最后使用 `Mockito.when` 来模拟静态方法的行为。 需要注意的是,使用 PowerMockito 进行静态方法模拟需要添加相应的依赖,否则会报 NoClassDefFoundError 错误。例如,使用 Maven 的项目需要添加以下依赖: ``` <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值