我在Java Spark中有简单的restfull api。获得单用户的单元测试按预期成功通过,而不是不存在用户的失败案例。 单元测试:
@Test
public void testGetNonExistingUser() {
String userId = "5284c69d-ab72-4703-ba84-ce4feafd456f";
Response response = request("GET", "/user/" + userId);
}
返回输出:
100 [Thread-0] INFO org.eclipse.jetty.util.log - Logging initialized @620ms
141 [Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - == Spark has ignited ...
141 [Thread-0] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >> Listening on 0.0.0.0:4567
143 [Thread-0] INFO org.eclipse.jetty.server.Server - jetty-9.3.6.v20151106
204 [Thread-0] INFO org.eclipse.jetty.server.ServerConnector - Started ServerConnector@575743e2{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
204 [Thread-0] INFO org.eclipse.jetty.server.Server - Started @725ms
2019-01-07 20:54:35 ERROR String:79 - checkIfIdAlreadyExists() User with id=5284c69d-ab72-4703-ba84-ce4feafd456f not exists
285 [qtp1828303595-19] INFO spark.http.matching.MatcherFilter - The requested route [/user/5284c69d-ab72-4703-ba84-ce4feafd456f] has not been mapped in Spark
java.io.FileNotFoundException: http://localhost:4567/user/5284c69d-ab72-4703-ba84-ce4feafd456f
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1909)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
(...)
300 [main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - >>> Spark shutting down ...
308 [main] INFO org.eclipse.jetty.server.ServerConnector - Stopped ServerConnector@575743e2{HTTP/1.1,[http/1.1]}{0.0.0.0:4567}
310 [main] INFO spark.embeddedserver.jetty.EmbeddedJettyServer - done
java.lang.AssertionError: Sending request failed: http://localhost:4567/user/5284c69d-ab72-4703-ba84-ce4feafd456f
at org.junit.Assert.fail(Assert.java:88)
at com.endpoints.moneyapp.utils.Utils.request(Utils.java:40)
(...)
正在spark中处理此异常的代码。
get("/user/:id", (request, response) -> userDAO.getUser(request.params(":id")), JSONUtil.json());
after((request, response) -> {
response.type("application/json");
});
exception(IllegalArgumentException.class, (exception, request, response) -> {
response.status(FAILED_RESPONSE);
response.body(JSONUtil.toJson(new ResponseError(exception)));
});
exception(CustomException.class, (exception, request, response) -> {
response.status(FAILED_RESPONSE);
response.body(JSONUtil.toJson(new ResponseError(exception)));
});
代码中有一个引发异常的地方。
private void checkIfIdAlreadyExists(String id) throws CustomException {
if (!users.containsKey(id)) {
String message = "User with id=" + id + " not exists";
throw new CustomException(message);
}
}
如何对不存在的用户进行正确的单元测试?