我在 quarkus 中编写了一个 Rest API,用于将英里转换为公里。
@GET
@Path("/miles-to-kilometers")
public Response milesToKilometers(@QueryParam("value") double miles) {
double kilometers = miles * 1.60934;
String answer = String.format("Kilometers: %.3f", kilometers);
int roundedKms = (int) Math.floor(kilometers);
if (roundedKms >= 0 && roundedKms <= 10) {
answer = answer.concat(" is below 10");
} else if (roundedKms >= 11 && roundedKms <= 20) {
answer = answer.concat(" is below 20");
} else if (roundedKms >= 21 && roundedKms <= 30) {
answer = answer.concat(" is below 30");
} else if (roundedKms >= 31 && roundedKms <= 40) {
answer = answer.concat(" is below 40");
} else if (roundedKms >= 41 && roundedKms <= 50) {
answer = answer.concat(" is below 50");
} else if (roundedKms >= 51) {
answer = answer.concat(" more than 50");
}
return Response.ok(payload, MediaType.TEXT_PLAIN).build();
}
对于上面的代码片段,我使用junit编写了一个测试用例
@ParameterizedTest
@ValueSource(doubles = { 1, 0, 5.0, 15.0, 25.0, 35.0, 45.0, 55.0, 2.688, 5.645, 11.789, 15.678, 20.678, 28.211,
35.212, 45.677 })
public void testMitoKm(double miles) {
String url = String.format("/miles-to-kilometers=%.2f", miles);
given()
.when().get(url)
.then()
.statusCode(200)
.body(containsString("Kilometers: "))
.body(containsString(getExpectedMessageForMiles(miles)));
}
private String getExpectedMessageForMiles(double miles) {
double kilometers = miles * 1.60934;
int roundedKms = (int) Math.floor(kilometers);
if (roundedKms >= 0 && roundedKms <= 10) {
return " is below 10";
} else if (roundedKms >= 11 && roundedKms <= 20) {
return " is below 20";
} else if (roundedKms >= 21 && roundedKms <= 30) {
return " is below 30";
} else if (roundedKms >= 31 && roundedKms <= 40) {
return " is below 40";
} else if (roundedKms >= 41 && roundedKms <= 50) {
return " unbelievable";
} else if (roundedKms >= 51) {
return " is below 50";
} else {
return "";
}
}
if 和 else if 分支仍然没有被 Jacoco 覆盖。 显示1/4分支未被覆盖。 在 else if 语句上给出黄色警告线。 如何覆盖 jacoco 中给定片段的所有分支?
在@ValueSource中我添加了一个负值-1。现在jacoco可以覆盖所有的分支了
@ParameterizedTest
@ValueSource(doubles = {-1, 1, 0, 2.688, 5.645, 11.789, 15.678, 20.678, 28.211,
35.212, 45.677 })
public void testMitoKm(double miles) {...}
在valuesource中添加-1后,jacoco可以覆盖所有else if条件。