[英]JUnit Testing: How to test a custom, empty java class that extends Exception?
我目前正在尝试扩展基于学校的作业 web 应用程序的测试覆盖率,因为我遇到了一个完全空的 class,它扩展了异常并且根据覆盖率报告不包含任何覆盖率。
通常,我会假设可以忽略这样的事情。 然而,我们的整体测试覆盖率因素直接影响到我们对这门课程的个人评分。 正因为如此,而且临近学期末,我正在尝试 go 逐行通过覆盖率报告中标记的代码,并尽我所能整理一切。
在浏览了课程内容并在线搜索之后,我不确定如何继续为这样的 class 编写测试。 这个服务器端 class 包含在我们的初始代码库中,该代码库是在学期开始时由讲师提供给我们的(我们随着学期的进展构建代码库)。
Java class 的完整代码:
package <package_name>;
/*
* This is a custom exception that fits our personal
* needs and won't collide with existing issues.
*/
public class BadRequestException extends Exception {}
如何使用 class 的一个示例(仍然是讲师提供的代码):
private String processHttpRequest(spark.Request httpRequest, spark.Response httpResponse, Type requestType) {
setupResponse(httpResponse);
String jsonString = httpRequest.body();
try {
JSONValidator.validate(jsonString, requestType);
Request requestObj = new Gson().fromJson(jsonString, requestType);
return buildJSONResponse(requestObj);
} catch (IOException | BadRequestException e) { // <---- Here
log.info("Bad Request - {}", e.getMessage()); // <----
httpResponse.status(HTTP_BAD_REQUEST);
} catch (Exception e) {
log.info("Server Error - ", e);
httpResponse.status(HTTP_SERVER_ERROR);
}
return jsonString;
}
到目前为止我所拥有的(几乎没有):
package <package_name>;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
public class TestBadRequestException {
@Test
@DisplayName("Test Empty BadRequestException Class")
public void testBadRequestException() {
}
}
在学期开始之前,我没有使用 JUnit 的经验。因此,非常感谢任何反馈/参考/建议。
这篇文章的第一条评论提供了我正在寻找的解决方案。 我没想到会这么简单。
解决方案在下面的答案中,并附有适当的信用。
我认为没有必要为 class 编写单元测试。 您可以尝试在代码覆盖规则中排除它
f1sh 的评论(原始解决方案)建议在 JUnit 测试中添加new BadRequestException()
。
这让我想到了如何改进该建议。
我的最终结果:
package <package_name>;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestBadRequestException {
@Test
@DisplayName("Test Empty BadRequestException Class")
public void testBadRequestException() {
assertNotNull(new BadRequestException()); // <---- Here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.