首页 > 解决方案 > 如何在 JUnit 测试中覆盖私有方法

问题描述

请帮助我如何在公共方法中使用我的类中的私有方法。每当我运行 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 上遗漏了哪些地方以涵盖私有方法“格式”。任何帮助都感激不尽。谢谢。

标签: javaspring-bootjunit

解决方案


testFormat,如果elasticsearchService.addRecord正在测试,它不应该被嘲笑。即删除Mockito.when(elasticsearchService.addRecord(null)).thenReturn("");

应该嘲笑的是方法中使用的服务/依赖项。例如loggingService

xxx

更新 #1:EclEmma 告诉您 if 语句的主体是红色的。这意味着testAddRecordIsNull没有正确配置。它正在传递一个具有值的 Record 对象。与其传球rec,不如传球new Record()。这假定新 Record 的属性具有默认值null。如果您需要一个包含其他属性值的记录,请相应地创建一个新记录。


推荐阅读