Java 模拟删除方法

Java 模拟删除方法,java,unit-testing,mocking,mockito,Java,Unit Testing,Mocking,Mockito,我想通过验证实现delete方法并对其进行测试: @Override public boolean delete(Long id) { final Entity byId = repository.findById(id); if (byId != null) { repository.delete(byId); } final Entity removed = repository.find

我想通过验证实现delete方法并对其进行测试:

    @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));
    }

但现在Mockito正在模拟服务中“删除”的对象,并且该方法返回false。如何测试它?

正如我从代码中看到的,您调用了方法
repository.findById
两次。但你并不是在考试中嘲笑这种行为。 您需要使用
然后返回
两次,第一次使用
实体
,然后使用

Mockito.when(repository.findById(1L)).thenReturn(entity).the‌​nReturn(null)

使用现有代码,当您执行
final Entity removed=repository.findById(id)时
remove
获取分配给
实体的值,且不为null。

您在代码中调用了
repository.findById
两次,因此需要
Mockito.when(repository.findById(1L))。然后返回(entity)。然后返回(null)
它可以工作。谢谢注意:
if(removed!=null)返回false;返回true
最好写为
returnremoved==null
。但作为一个更一般的问题:
repository.delete
为什么不在下次尝试查找时使元素不为空?如果存储库的实现还不能保证这一点,那么它似乎是有缺陷的。与中一样,您似乎在这里测试了错误的单元:在repository类的单元测试中测试它,而不是在这个类中。断言测试中调用了
repository.delete
,但不要依赖于delete方法的实现。