Skip to content

Instantly share code, notes, and snippets.

@mcantrell
Last active October 9, 2015 23:57
Show Gist options
  • Save mcantrell/3599362 to your computer and use it in GitHub Desktop.
Save mcantrell/3599362 to your computer and use it in GitHub Desktop.
Mocking HTTP Server Responses in Junit
import org.junit.AfterClass
import org.junit.BeforeClass
import org.mortbay.jetty.Server
import org.springframework.core.io.ClassPathResource
abstract class BaseHttpServerIntegrationTest {
static Server server
@BeforeClass
static void createServer() {
server = new Server(8081)
def resources = [
"/zuul/settings/prod/app-data-config.properties" :new ClassPathResource("/mock-server-response.properties")
]
server.handler = new ResourceRequestHandler(resources: resources)
server.start()
}
@AfterClass
static void stopServer() {
server.stop()
}
}
<!-- part of pom.xml -->
<dependencies>
<!-- for embedded http server testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
import org.mortbay.jetty.handler.AbstractHandler
import org.springframework.core.io.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class ResourceRequestHandler extends AbstractHandler {
Map<String, Resource> resources
void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) {
response.status = HttpServletResponse.SC_OK
response.outputStream << resources[target].inputStream
}
}
@mcantrell
Copy link
Author

Useful for mocking out http client requests when testing web services, etc..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment