我有這樣的單元測試:JUnit的驗證方法從不運行路過時應該失敗
@RunWith (MockitoJUnitRunner.class)
public class RefChangEventTest {
@Mock
RefChange ref;
@Mock
SEPCommits sepCommits;
@Mock
SEPRefChangeEvent sepRefChangeEvent;
@Mock
RepositoryRefsChangedEvent refsChangedEvent;
@Mock
Repository repo;
@Test
public void gitNotesAreIgnored() throws Exception {
Collection<RefChange> refList = new ArrayList<RefChange>(1);
ArrayList commitListMock = mock(ArrayList.class);
refList.add(ref);
when(refsChangedEvent.getRefChanges()).thenReturn(refList);
when(refsChangedEvent.getRepository()).thenReturn(repo);
when(ref.getRefId()).thenReturn("refs/heads/foo");
when(sepRefChangeEvent.makeArrayList()).thenReturn(commitListMock);
sepRefChangeEvent.processEvent(refsChangedEvent);
verify(sepCommits, never()).findCommitInfo(ref, repo, commitListMock);
}
}
和源代碼,以匹配它是在這裏:
public ArrayList<Message> makeArrayList() {
return new ArrayList<Message>();
}
@Override
public List<Message> processEvent(RepositoryRefsChangedEvent event) {
ArrayList<Message> commitList = makeArrayList();
for (RefChange refChange : event.getRefChanges()) {
LOGGER.info("checking ref change refId={} fromHash={} toHash={} type={}", refChange.getRefId(), refChange.getFromHash(),
refChange.getToHash(), refChange.getType());
if (refChange.getRefId().startsWith(REF_BRANCH)) {
if (refChange.getType() == RefChangeType.ADD && isDeleted(refChange)) {
LOGGER.info("Deleted a ref that never existed. This shouldn't ever occur.");
}
else if (isDeleted(refChange) || isCreated(refChange)) {
branchCreation(refChange, event.getRepository(), commitList);
}
else {
sepCommits.findCommitInfo(refChange, event.getRepository(), commitList);
}
}
else {
LOGGER.info("This type of refChange is not supported.\n refId={} fromHash={} toHash={} type={}", refChange.getRefId(), refChange.getFromHash(),
refChange.getToHash(), refChange.getType());
}
}
return commitList;
}
我寫失敗了測試。 refID是refs/heads/foo
並且應該調用我測試的方法不應該被調用。但是,當我運行這個測試時,它會以絢麗的色彩通過。我在哪裏搞亂?
是的我知道PowerMockito可以模擬構造函數,我做了簡單的makeArrayList()
方法來快速編寫這個單元測試。
請發佈全班。我看到的是你從來沒有從測試中設置類字段 –