Clone wiki

fakehttpserver / Home

Fake HTTP Server

Introduction

httpfakeserver is a java library written to aid in writing clean HTTP client tests using JUnit.

You create a fake server, give it some expectations of what types of requests it should receive, and the type of responses it should return. The expectations are asserted after each test has been run, and the fake server is automatically stopped.

The easiest way to see how it works is, as always, with some examples.

Example

package se.dannej.someproject.integrationtest;

import static se.dannej.fakehttpserver.expect.ResponseActions.sendStatus;
import static se.dannej.fakehttpserver.expect.matcher.RequestMatchers.path;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import se.dannej.fakehttpserver.FakeHttpServer;
import se.dannej.fakehttpserver.JettyFakeServer;
import se.dannej.fakehttpserver.expect.Expectations;
import se.dannej.fakehttpserver.junit.FakeServerRule;
import se.dannej.someproject.ObjectToTest;

// Set up the Spring runner as you would normally do
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {

  // Create a fake server that listens to port 6666
  private final FakeHttpServer server = new JettyFakeServer(6666);

  // Create a FakeServer JUnit rule
  @Rule
  public final FakeServerRule rule = new FakeServerRule();

  // Inject bean to test
  @Autowired
  private ObjectToTest objectToTest;

  @Test
  public void postsToPath() {
    // Start the server
    server.start();

    // Add some expectations on the server
    new Expectations() {{
      oneOf(server).post().with(path("/"));
        will(sendStatus(201));
    }};

    // Invoke the method to test
    objectToTest.post("/");
  }
}

General

Expectations

Expectations can be added either before or after the server has been started.

For more information on how to use it, see:

Maven

The library is available in the central repository. Add the following to your pom file:

  <dependency>
    <groupId>se.dannej</groupId>
    <artifactId>fakehttpserver</artifactId>
    <version>0.3.0</version>
  </dependency>

Updated