我現在被困在洗掉測驗中。
這里是 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)
我真的不知道我犯了什么錯誤,任何幫助將不勝感激。謝謝!
uj5u.com熱心網友回復:
您正在檢查是否
postRespository.deleteById(1l);
在這里被呼叫一次
Mockito.verify(postRepository, Mockito.times(1)).deleteById(1L);
但是您的 PostServiceImpl.class 沒有呼叫該方法。它正在呼叫
postRepository.delete(post);
它將 Post 類作為引數。將驗證陳述句更改為
Mockito.verify(postRepository, Mockito.times(1)).delete(post);
它應該可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470370.html