use*_*ser 3 java unit-testing mocking mockito
我想通过验证实现删除方法并测试它:
@Override
public boolean delete(Long id) {
final Entity byId = repository.findById(id);
if (byId != null) {
repository.delete(byId);
}
final Entity removed = repository.findById(id);
if (removed != null) {
return false;
}
return true;
}
@Test
public void deleteTest() throws Exception {
// given
final Entity entity = new Entity(1L);
Mockito.when(repository.findById(1L))
.thenReturn(entity);
// when
final boolean result = service.delete(1L);
// then
Mockito.verify(repository, times(1))
.delete(entity);
assertThat(result, equalTo(true));
}
Run Code Online (Sandbox Code Playgroud)
但现在 Mockito 正在模拟服务中“删除”的对象,并且方法返回 false。我该如何测试它?
正如我从您的代码中看到的,您调用了该方法repository.findById两次。但你并没有在测试中嘲笑这种行为。\n您需要使用thenReturn两次,第一次是 with entity,然后是 withnull
Mockito.when(repository.findById(1L)).thenReturn(entity).the\xe2\x80\x8c\xe2\x80\x8bnReturn(null)\nRun Code Online (Sandbox Code Playgroud)\n\n使用现有代码,当您执行 时final Entity removed = repository.findById(id);, 会remove被分配为entity且不为空。
| 归档时间: |
|
| 查看次数: |
20365 次 |
| 最近记录: |