2017-10-13 45 views

回答

0

使用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); 
    } 
} 
相關問題