Can use simple implementation of the LocalServer
public class LocalHttpServer extends ExternalResource {
private static final Logger log = LoggerFactory.getLogger(LocalHttpServer.class);
private final int port;
private MockServer server;
public LocalHttpServer(int port) {
this.port = port;
}
@Override
protected void before() throws Throwable {
server = new MockServer();
server.setUp();
}
public void start() throws Exception {
server.start(port);
log.info("LocalHttpServer started on {}", port);
}
/**
* Need to be setup before starting server
*/
public LocalHttpServer registerSimpleHandler(String path, String resp) {
server.registerSimpleHandler(path, resp);
return this;
}
@Override
protected void after() {
try {
server.shutDown();
} catch (Exception e) {
e.printStackTrace();
}
log.info("LocalHttpServer shutdown on {}", port);
}
static class MockServer extends LocalServerTestBase {
@Override
public void setUp() throws Exception {
super.setUp();
HttpRequestFactory requestFactory = new DefaultHttpRequestFactory() {
@Override
public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException {
return super.newHttpRequest(requestline);
}
};
HttpMessageParserFactory<HttpRequest> requestParserFactory = new DefaultHttpRequestParserFactory(
BasicLineParser.INSTANCE, requestFactory);
DefaultBHttpServerConnectionFactory connectionFactory = new DefaultBHttpServerConnectionFactory(
ConnectionConfig.DEFAULT, requestParserFactory, DefaultHttpResponseWriterFactory.INSTANCE);
this.serverBootstrap.setConnectionFactory(connectionFactory);
}
public void registerSimpleHandler(String path, String resp) {
this.serverBootstrap.registerHandler(path, (request, response, context) ->
response.setEntity(new StringEntity(resp, ContentType.TEXT_PLAIN)));
}
public void start(int port) throws Exception {
this.serverBootstrap.setListenerPort(port);
start();
}
}
Example usage
public class HttpTest {
private static final LocalHttpServer LOCAL_HTTP = new LocalHttpServer(8080);
@ClassRule
public static final RuleChain RULE_CHAIN = RuleChain.outerRule(LOCAL_HTTP);
@Before
public void setUp() throws Exception {
LOCAL_HTTP.registerSimpleHandler("/path", "response")
.start();
}
@Test
public void someTest() {
//request here
}
}