-
Notifications
You must be signed in to change notification settings - Fork 1
HTTP
Mock Socket HTTP module provides Mockito style mocking abilities for HTTP connection testing.
Add the following dependency to your build system
<dependency>
<groupId>net.javacrumbs</groupId>
<artifactId>mock-socket-http</artifactId>
<version>0.9.0</version>
</dependency>
First of all, you have to use the following import
import static net.javacrumbs.mocksocket.http.HttpMockSocket.*;
Then you can tell the mock what to do. There are two modes. The first on is sequential:
expectCall()
.andReturn(response().withContent("Test"))
.andReturn(response().withStatus(404));
This way you can teach the mock that it should expect two requests and that it should return HTTP status 200 for the first one together with "Test" response. It will also return HTTP status 404 as the second response.
It's also possible to validate the request content.
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
assertThat(recordedConnections().get(0), method(is("GET")));
assertThat(request(0).getMethod(), is("GET"));
assertThat(request(0).getAddress(), is("localhost:80"));
Sometimes we can not predict the order of request beforehand. In this case we can use matcher based mock.
expectCall()
.andWhenRequest(uri(is("/test/something.do"))).thenReturn(response().withStatus(404))
.andWhenRequest(uri(is("/test/other.do"))).thenReturn(response().withContent("Text"));
This way we can define, that the first request coming to URI "/test/something.do" should return 404 and second request to "/test/other.do" should return OK response with content "Text". Please note, that any consecutive request to the same URI will end up with an exception. If you want to support more requests, you have to call thenReturn() multiple times
@After
public void reset()
{
HttpMockSocket.reset();
}