删除方法的 JUnit ServiceTest 告诉我需要但未调用

JUnit ServiceTest for delete method which tells me Wanted but not invoked

我现在卡在删除测试中了。

下面是PostServiceImpl.class

的删除方法
@Override
public void deletePostById(Long id) {
    Post post = postRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("post", "id", id));

    postRepository.delete(post);
}

PostServiceTest.class

@BeforeEach
public void setup() {
    postDto = new PostDto();
    postDto.setId(1L);
    postDto.setTitle("test title");
    postDto.setDescription("test description");
    postDto.setContent("test content");

    post = new Post();
    post.setId(1L);
    post.setTitle("test title");
    post.setDescription("test description");
    post.setContent("test content");
}

@Test
void givenPostId_whenDeletePost_thenNothing() {

    Long postId = 1L;

    BDDMockito.given(postRepository.findById(postId))
            .willReturn(Optional.of(post));

    BDDMockito.willDoNothing().given(postRepository).deleteById(postId);

    postService.deletePostById(postId);

    Mockito.verify(postRepository, Mockito.times(1)).findById(1L);
    Mockito.verify(postRepository, Mockito.times(1)).deleteById(1L);
}

这是输出:

Wanted but not invoked:
postRepository.deleteById(1L);
-> at com.springboot.blog.service.PostServiceTest.givenPostId_whenDeletePost_thenNothing(PostServiceTest.java:148)

However, there were exactly 2 interactions with this mock:
postRepository.findById(1L);
-> at com.springboot.blog.service.PostServiceImpl.deletePostById(PostServiceImpl.java:95)

postRepository.delete(
Post(id=1, title=test title, description=test description, content=test content, createdTime=null, updatedTime=null));
-> at com.springboot.blog.service.PostServiceImpl.deletePostById(PostServiceImpl.java:98)

我真的不知道自己犯了什么错误,如有任何帮助,我们将不胜感激。 谢谢!

您正在检查是否

postRespository.deleteById(1l);

这里被调用一次

Mockito.verify(postRepository, Mockito.times(1)).deleteById(1L);

但是您的 PostServiceImpl.class 没有调用该方法。它正在调用

postRepository.delete(post);

以 Post class 作为参数。将验证语句改为

Mockito.verify(postRepository, Mockito.times(1)).delete(post);

它应该可以工作。