Skip to content
This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
dart0 edited this page Jul 9, 2011 · 7 revisions

Introduction

Mock Socket HTTP module provides Mockito style mocking abilities for HTTP connection testing.

Dependency

Add the following dependency to your build system

<dependency>
    <groupId>net.javacrumbs</groupId>
    <artifactId>mock-socket-http</artifactId>
    <version>0.9.0</version>
</dependency>

API

First of all, you have to use the following import

import static net.javacrumbs.mocksocket.http.HttpMockSocket.*;

Sequential mock

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.

Request validation

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"));

Matcher based mock

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

Cleanup

@After
public void reset()
{
	HttpMockSocket.reset();
}
Clone this wiki locally