java - 如何在 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 上遗漏了哪些地方以涵盖私有方法“格式”。任何帮助都感激不尽。谢谢。
解决方案
在testFormat
,如果elasticsearchService.addRecord
正在测试,它不应该被嘲笑。即删除Mockito.when(elasticsearchService.addRecord(null)).thenReturn("");
应该嘲笑的是方法中使用的服务/依赖项。例如loggingService
xxx
更新 #1:EclEmma 告诉您 if 语句的主体是红色的。这意味着testAddRecordIsNull
没有正确配置。它正在传递一个具有值的 Record 对象。与其传球rec
,不如传球new Record()
。这假定新 Record 的属性具有默认值null
。如果您需要一个包含其他属性值的记录,请相应地创建一个新记录。
推荐阅读
- android - 为什么 MediaPlayer 不能正确播放音频?
- tensorflow - Tensorflow Object-Detection API - 超参数调整和网格搜索
- c++ - CreateDIBSection() 失败 - 如何诊断
- sql-server - 如何使用 SQL Server (TSQL) 根据前行值更改/版本历史记录生成记录
- python - 通过避免 NaN 来滚动一个系列
- reactjs - 防止 Graphiql 控制台发出多个自省查询
- python - 关于如何解析带有树节点的 csv 的建议
- vue.js - Vue:Stripe 未定义 - 是否需要在任何地方都包含 Stripe?
- javascript - 如何处理异步/等待格式的回调函数的多个参数?
- pandas - 如何加速 Pandas 的“iterrows”