可选类型的单元测试用例

时间:2019-11-25 10:08:32

标签: java junit junit4 junit5

这是我的原始方法:

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);
}

2 个答案:

答案 0 :(得分:0)

我相信,最简单的方法是使用unitList,例如在filter操作之后,流将为空,即,其任何单元都不应使用相同的度量名称。

在这种情况下,findFirst将按照其文档中的说明返回Optional.empty()

最简单的方法是:

Mockito.when(uomService.getUnits()).thenReturn(Collections.emptyList()))

答案 1 :(得分:0)

您正在将我们发送给越来越多的最终提供一些数据的方法的麻烦。

这是您通常编写此类内容的方式。

class MyService {
    CrsService crsService;
    UnitService unitService;

public Unit getUnitSymbolForCRSCode(Integer crsCode) {  
    String crsUnitName = crsService.getCrsByCode(crsCode).getUnitName();
    return unitService.getUnits().stream()
                    .filter(u->u.getUnitOfMeasureName().equalsIgnoreCase(crsUnitName))
                    .findFirst()
                    .orElseThrow(() -> 
                                 new DataNotFoundException(String.format(
                                     "Failed to retrieve unit details for %s.",crsUnitName));
}

这就是您对其进行测试的方式(JUnit 5):

@ExtendWith(MockitoExtension.class)
class MyServiceTest {
    @Mock crsService;
    @Mock unitService;
    @InjectMocks MyService;

    @Test
    void testNoDataException() {
        CRS crs = mock(CRS.class);
        when(crsService.getCrsByCode(any())).thenReturn(crs);
        when(unitService.getUnits()).thenReturn(Collections.emptyList());

        assertThrows(DataNotFoundException.class,
                     () -> sut.getUnitSymbolForCRSCode(123));
    }
}

出于完整性考虑,这就是您稍后发布的CrsServiceUnitService

class FixedUnitService implements UnitService {
    public List<Unit> getUnits() {
        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;
    }
}
class LookupCrsService implements CrsService {
    public Crs getCrsByCode(int id) {
        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);
    }
}

您可以完全单独测试这些类。