美文网首页
单元测试

单元测试

作者: Fans2017 | 来源:发表于2023-06-24 17:07 被阅读0次

好处1:为代码重构保驾护航
好处2:既是编写单测也是CodeReview
好处3:便于调试与验证
好处4:驱动设计与重构

单元测试规范
1、建议采用should_{预期结果}when{被测方法}given{给定场景}
2、建议采用given-when-then的三段落结构

@RunWith(MockitoJUnitRunner.Silent.class)
public class ContentServiceTest {

@Mock
DocManageService docManageService;

@InjectMocks
ContentService contentService;

@Test
public void should_returnFalse_when_deleteContent_given_invokeFailed() {
// given
Result<Boolean> deleteDocResult = new Result<>();
deleteDocResult.setEntity(Boolean.FALSE);
when(docManageService.deleteContentDoc(anyLong())).thenReturn(deleteDocResult);
when(docManageService.queryContentDoc(anyLong())).thenReturn(new DocEntity());

// when
Long contentId = 123L;
Boolean result = contentService.deleteContent(contentId);

// then
verify(docManageService, times(1)).queryContentDoc(contentId);
verify(docManageService, times(1)).deleteContentDoc(contentId);
Assert.assertFalse(result);

}
}

相关文章

网友评论

      本文标题:单元测试

      本文链接:https://www.haomeiwen.com/subject/lfpbydtx.html