单元测试

好处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);

}
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容