【发布时间】:2019-11-25 10:08:32
【问题描述】:
这是我原来的方法:
public Unit getUnitSymbolForCRSCode(Integer crsCode) {
String crsUnitName = getCrsByCode(crsCode).getUnitName();
List<Unit> unitList = getUnits();
Optional<Unit> unit = unitList.stream().filter(u->u.getUnitOfMeasureName().equalsIgnoreCase(crsUnitName)).findFirst();
if(!unit.isPresent()){
throw new DataNotFoundException(String.format("Failed to retrieve unit details for %s.",crsUnitName));
}
return unit.get();
}
在为它编写如下所示的测试用例时,没有涵盖一个分支。我无法抛出 DataNotFoundException。
@Test
public void testGetUnitSymbolForCRSCodeThrowingDataNotFoundException() {
Unit unitObj = new Unit();
Mockito.when(geoCalService.search(Mockito.any(SearchFilter.class)))
.thenReturn(TestDataFactory.getSearchResultResponseForCRS());
Mockito.when(uomService.getUnits()).thenReturn(Arrays.asList(unitObj));
thrown.expect(DataNotFoundException.class);
shellGeodeticService.getUnitSymbolForCRSCode(50015);
}
我遇到了类似的错误
java.lang.AssertionError: Expected test to throw an instance of com.shell.geodetic.exception.DataNotFoundException.
虽然 UnitObj 是空的,但它不会抛出 DataNotFoundException。请帮忙。
public static List<Unit> getUnitList() {
List<Unit> unitList= new ArrayList<Unit>();
unitList.add(new Unit("dega","Degree"));
unitList.add(new Unit("ft[US]","US Survey foot"));
unitList.add(new Unit("m","Meter"));
unitList.add(new Unit("ft[Se]","Sear's Foot"));
unitList.add(new Unit("ft[GC]","Gold Coast Foot"));
unitList.add(new Unit("ft","International Foot"));
unitList.add(new Unit("link[Cla]","Clarke's Link"));
unitList.add(new Unit("gon","Grad"));
return unitList;
}
public CRS getCrsByCode(Integer code) {
SearchResultResponse response = searchCode(String.valueOf(code), 180224);
List<DisplayItem> crsDisplayItems = response.getDisplayItems();
if (crsDisplayItems.isEmpty()) {
throw new DataNotFoundException("CRS not found with code " + code + ": " + response.getSearchMessage());
}
return Util.convertToCrsVoList(crsDisplayItems).get(0);
}
【问题讨论】:
-
您确实需要发布
getUnits()方法。我假设它调用您正在嘲笑的geoCalService.search()。此外,从您的代码来看,您不会得到空的或不匹配的结果,这并不明显;也许你应该为此定义一个单独的测试用例,而不使用TestDataFactory。 -
我添加的 getUnits 代码。是的,它在内部调用了 seach() 方法。此外,它总是返回匹配的结果。所以我需要为非匹配结果编写一个测试,其中 if(!unit.isPresent()){} 条件将变为真并抛出 DataNotFoundException