Как покрыть приватный метод в JUnit Testing - PullRequest
0 голосов
/ 13 апреля 2020

Пожалуйста, помогите мне, как я собираюсь покрыть приватный метод в моем классе, используемый в методе publi c. Всякий раз, когда я запускаю свое покрытие JUnit, оно говорит, что у этого закрытого метода есть отсутствующая ветвь.

Вот код, который использует этот закрытый метод:

public String addRecord(Record rec) throws IOException {
    GeoPoint geoPoint = locationService.getLocation(rec.getTerminalId());
    if (Objects.isNull(geoPoint)) {
        loggingService.log(this.getClass().toString(), rec.getTerminalId(), "GET LOCATION",
                "No Coordinates found for terminal ID: " + rec.getTerminalId());
        return "No Coordinates found for terminal ID: " + rec.getTerminalId();
    }
    loggingService.log(this.getClass().toString(), rec.getTerminalId(), "GeoPoint",
            "Latitude: " + geoPoint.getLat() + " Longitude: " + geoPoint.getLon());
    format(rec);
    loggingService.log(this.getClass().toString(), rec.getTerminalId(), "addRecord",
            "Formatted Payload" + rec.toString());

    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject().field("terminalId", rec.getTerminalId())
            .field("status", "D".equals(rec.getStatus()) ? 1 : 0).field("recLocation", rec.getLocation())
            .field("errorDescription", rec.getErrorDescription()).field("lastTranTime", rec.getLastTranTime())
            .field("lastDevStatTime", rec.getLastDevStatTime()).field("errorCode", rec.getErrorCode())
            .field("termBrcode", rec.getTermBrcode()).timeField("@timestamp", new Date())
            .latlon("location", geoPoint.getLat(), geoPoint.getLon()).endObject();

    IndexRequest indexRequest = new IndexRequest(prop.getEsIndex(), prop.getEsType(), rec.getTerminalId())
            .source(builder);
    IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
    loggingService.log(this.getClass().toString(), rec.getTerminalId(), TraceLog.SUCCESSFUL_PUSH_TO_ELASTIC_SEARCH,
            util.mapToJsonString(rec));

    return response.getResult().name();
}

Это закрытый метод:

private Record format(Record rec) {
    if (rec.getLocation() == null) {
        rec.setLocation("");
    }
    if (rec.getTermBrcode() == null) {
        rec.setTermBrcode("");
    }
    if (rec.getErrorDescription() == null) {
        rec.setErrorDescription("");
    }
    return rec;
}

Это мой код Junit:

@Before
public void setUp() throws ParseException, IOException {

    client = mock(RestHighLevelClient.class);
    indexRequest = mock(IndexRequest.class);
    indexResponse = mock(IndexResponse.class);

    MockitoAnnotations.initMocks(this);
    rec= new Record();
    rec.setLocation("location");
    rec.setStatus("U");
    rec.setErrorCode("222");
    rec.setErrorDescription("STATUS");
    rec.setLastDevStatTime("02-02-2020");
    rec.setLastTranTime("02-02-2020");
    rec.setTerminalId("123");
    rec.setTermBrcode("111");

    ReflectionTestUtils.setField(client, "client", restClient);
}

@Test
public void testAddRecordIsNull()
        throws IOException, NumberFormatException, IllegalArgumentException, IllegalAccessException {
    Mockito.when(locationService.getLocation(Mockito.anyString())).thenReturn(null);
    elasticsearchService.addRecord(rec);
    assertThat(1).isEqualTo(1);
}

@Test
public void testFormat() throws IOException {
    rec = new Record();
    rec.setLocation(null);
    rec.setStatus(null);
    rec.setErrorCode(null);
    rec.setErrorDescription(null);
    rec.setLastDevStatTime(null);
    rec.setLastTranTime(null);
    rec.setTerminalId(null);
    rec.setTermBrcode(null);
    elasticsearchService.addRecord(rec);
    //ReflectionTestUtils.invokeMethod(ElasticsearchService.class, "addAtmStatusRecord", rec);
    Mockito.when(elasticsearchService.addRecord(null)).thenReturn("");
    //elasticsearchService.addRecord(atm);
    //Mockito.when(locationService.getLocation(Mockito.anyString())).thenReturn(atm);
    //elasticsearchService.addRecord(null);
    assertThat(1).isEqualTo(1);
}

Пожалуйста, помогите мне, где мне не хватает в моем JUnit, чтобы покрыть закрытый метод 'format'. Любая помощь будет высоко ценится. Спасибо.

Ответы [ 2 ]

0 голосов
/ 13 апреля 2020

Да! Я наконец нашел решение.

@Test
public void testFormat() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    rec= new Record();
    rec.setLocation(null);
    rec.setStatus(null);
    rec.setErrorCode(null);
    rec.setErrorDescription(null);
    rec.setLastDevStatTime(null);
    rec.setLastTranTime(null);
    rec.setTerminalId(null);
    rec.setTermBrcode(null);

    java.lang.reflect.Method method = ElasticsearchService.class.getDeclaredMethod("format", Record.class);
    method.setAccessible(true);
    Record output = (Record) method.invoke(es, rec);
    assertEquals(output, rec);

}

Отражение - это ключ. Разделите это здесь, чтобы другие, работающие над той же проблемой, могли получить это для помощи. Спасибо.

0 голосов
/ 13 апреля 2020

В testFormat, если проверяется elasticsearchService.addRecord, это не должно быть издевательским. то есть Remove Mockito.when(elasticsearchService.addRecord(null)).thenReturn("");

То, что нужно смоделировать, это службы / зависимости, используемые в методе. Например, loggingService

xxx

Обновление № 1: EclEmma сообщает вам, что тело оператора if имеет красный цвет. Это означает, что testAddRecordIsNull настроен неправильно. Он передает объект Record, который имеет значения. Вместо передачи rec, передайте new Record(). Это предполагает, что атрибуты новой записи имеют значения по умолчанию null. Если вам нужна запись, которая имеет значения для других атрибутов, создайте новую запись соответственно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...