好處1:為代碼重構(gòu)保駕護(hù)航
好處2:既是編寫單測也是CodeReview
好處3:便于調(diào)試與驗(yàn)證
好處4:驅(qū)動(dòng)設(shè)計(jì)與重構(gòu)
單元測試規(guī)范
1、建議采用should_{預(yù)期結(jié)果}when{被測方法}given{給定場景}
2俐筋、建議采用given-when-then的三段落結(jié)構(gòu)
@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);
}
}