I am stuck at a delete test now.
Here is the delete method of 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);
}
and this is the output:
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)
I do not really know what mistakes I made and any assistance would be appreciated. Thanks!
CodePudding user response:
You are checking whether
postRespository.deleteById(1l);
is being called once here
Mockito.verify(postRepository, Mockito.times(1)).deleteById(1L);
But your PostServiceImpl.class is not calling that method. It is calling the
postRepository.delete(post);
which takes the Post class as parameter. Change the verification statement to
Mockito.verify(postRepository, Mockito.times(1)).delete(post);
and it should work.
CodePudding user response:
Have you try to seperate method for method deletebyId and FindById? Because find by should return/retrieve data and delete will look for that value and be deleted.