caso_prueba unidad para el tipo opcional

arun:

Este es mi método original:

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

Mientras escribe un caso de prueba para él, como a continuación, una rama no está cubierto. No se puede obtener im DataNotFoundException arrojados.

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

Im que consigue error como

java.lang.AssertionError: Expected test to throw an instance of com.shell.geodetic.exception.DataNotFoundException. 

Aunque UnitObj está vacío, no es tirando DataNotFoundException. Por favor asiste.

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

Nos va a enviar en un agujero de conejo de más y más métodos que en última instancia proporcionan algunos datos.

Así es como se escribe en general, este tipo de cosas.

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

y así es como lo prueba (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));
    }
}

Para completarlo, este sería el CrsServicey UnitServicecomo lo publicado después:

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

Puede probar estas clases de forma completamente independiente.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=362321&siteId=1
Recomendado
Clasificación