簡體   English   中英

如何在 JUnit 測試中覆蓋私有方法

[英]How to cover a private method in JUnit Testing

請幫助我如何在公共方法中使用的 class 中介紹私有方法。 每當我運行我的 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 上遺漏了哪些地方以涵蓋私有方法“格式”。 任何幫助都感激不盡。 謝謝。

testFormat中,如果正在測試elasticsearchService.addRecord ,則不應對其進行模擬。 即刪除Mockito.when(elasticsearchService.addRecord(null)).thenReturn("");

應該嘲笑的是方法中使用的服務/依賴項。 例如loggingService

xxx

更新 #1:EclEmma 告訴您 if 語句的主體是紅色的。 這意味着未正確配置testAddRecordIsNull 它正在傳遞具有值的記錄 object。 而不是傳遞rec ,傳遞new Record() 這假設新記錄的屬性具有默認值null 如果您需要一個包含其他屬性值的記錄,請相應地創建一個新記錄。

是的。 我終於找到了解決方案。

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

}

反思是關鍵。 在這里分享它,以便其他在同一問題上運行的人可能會得到幫助。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM