好处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);
}
}
网友评论