0
我的單元測試調用了進行http交互的組件。我想在運行測試之前設置一個http服務器,然後在測試之後做出斷言,看看是否發生了預期的交互。什麼是在java單元測試中設置http服務器並對其進行斷言的快速方法?
嘲笑是由於幾個原因,包括我想鍛鍊網絡互動作爲測試的一部分太低的水平。
我的單元測試調用了進行http交互的組件。我想在運行測試之前設置一個http服務器,然後在測試之後做出斷言,看看是否發生了預期的交互。什麼是在java單元測試中設置http服務器並對其進行斷言的快速方法?
嘲笑是由於幾個原因,包括我想鍛鍊網絡互動作爲測試的一部分太低的水平。
使用Simple Framework,您可以通過gradle這個像這樣包括:
testCompile 'org.simpleframework:simple:5.+'
你可以寫一個測試用例是這樣的:
public class HttpMockingTest {
class TestContainer implements Container {
int n = 0;
@Override
public void handle(Request req, Response resp) {
// count
n += 1;
// close the response
try {
resp.getOutputStream().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void test0() throws IOException {
// this sets up the server
TestContainer testContainer = new TestContainer();
Server server = new ContainerServer(testContainer);
SocketConnection socketConnection = new SocketConnection(server);
InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 9999);
socketConnection.connect(inetSocketAddress);
// this invokes the server
int n = 2;
for (int i = 0; i < n; i++) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet("http://localhost:9999/foo"));
}
}
// make assertions
assertEquals(n, testContainer.n);
}
}