Javaマイクロサービスに安らかなAPIを追加しようとしています。私は、APIを立ち上がる非常に単純なクラスを作成しましたユニットテストJava Sparkマイクロフレーム
http://sparkjava.com/documentation.html
:このため、私は火花を使用しています。そのクラスはここにある:今
public class Routes {
public void establishRoutes(){
get("/test", (req, res) -> "Hello World");
after((req, res) -> {
res.type("application/json");
});
exception(IllegalArgumentException.class, (e, req, res) -> {
res.status(400);
});
}
、誰かがhttp://localhost:4567/testを訪問することを決定したイベントでの「Hello World」を示すだろうAPIを立たなければならない()Routes.establishRoutesを実行しています。これは実際には機能します。ハレイ!
次のステップは、コードの単体テストです。私のユニットテストは、残念ながら成功しません。スパークのドキュメンテーションは、テストのための健全な方法を詳述していないので、私が持っているものは、ネットの周りに見いだされた例からまとめられています。ここに私のJUnitテストがある:
public class TestRoutes {
@Before
public void setUp() throws Exception {
Routes newRoutes = new Routes();
newRoutes.establishRoutes();
}
@After
public void tearDown() throws Exception {
stop();
}
@Test
public void testModelObjectsPOST(){
String testUrl = "/test";
ApiTestUtils.TestResponse res = ApiTestUtils.request("GET", testUrl, null);
Map<String, String> json = res.json();
assertEquals(201, res.status);
}
ここApiTestUtils.requestの背後にあるコードは)(です:
public class ApiTestUtils {
public static TestResponse request(String method, String path, String requestBody) {
try {
URL url = new URL("http://localhost:4567" + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.connect();
String body = IOUtils.toString(connection.getInputStream());
return new TestResponse(connection.getResponseCode(), body);
} catch (IOException e) {
e.printStackTrace();
fail("Sending request failed: " + e.getMessage());
return null;
}
}
public static class TestResponse {
public final String body;
public final int status;
public TestResponse(int status, String body) {
this.status = status;
this.body = body;
}
public Map<String,String> json() {
return new Gson().fromJson(body, HashMap.class);
}
}
}
私はApiTestUtils.request()
内connection.connect()
に失敗しています。具体的には、次のエラーが表示されます。java.lang.AssertionError: Sending request failed: Connection refused
私のテストがリクエストを行おうとしたときにアプリケーションがリッスンしていないと考えられます。しかし、なぜそうなるのか分かりません。私はここで見つけるデモプロジェクトからテストコードを借り: https://github.com/mscharhag/blog-examples/blob/master/sparkdemo/src/test/java/com/mscharhag/sparkdemo/UserControllerIntegrationTest.java
はUPDATE: 私は上記のリンクの例を実行してみました。それはうまくいかない。この文脈でスパークのインスタンスを回転させるように見えるのは、私が思ったよりも難しいでしょうか?私はそうする方法を見つけようとはしていない。
を呼び出すことによって、初期化のために待つことです。あなたはそのコードで何をしようとしているのは後者です。単体テストは、例えばTestメソッドで直接 'establishRoutes'を呼び出し、戻り値や副作用を確認します。 – david
十分です。あなたはjunitが統合テストのための不適切な場所だと感じますか? – melchoir55
Junitはこれで問題ありません。あなたはあなたのサーバーを起動することを確認する必要があります。あなたはどこにいても好きではありません。この例では、 'Main'の使用を見てください。 – david