MockHttpServer for Testing Android HTTP Client
While developing an Android project, I needed to test an HTTP client service layer running in my application. I wanted to ensure I unit tested features such as ability to send/receive headers, request http resources, and deal with HTTP response codes properly. However, I did not want to run my JUnit tests using an external HTTP server. This would create a dependency on yet another technology that I would have to launch with Maven. Furthermore, using an external server would make it difficult to validate unit test cases from the server side.
MockHttpServer
You may already know that Android’s library comes with a version of Apache’s HttpComponent. While Android promotes the use of HttpComponent for mostly client side development, the provided APIs include the server-side pieces as well. So, you can create your own HTTP server running on Android.
MockHttpServer is a wrapper around the HttpComponent’s HttpService API. MockHttpServer provides a simple interaction point where developers simply provide an implementation of HttpRequestHandler.
The MockHttpServer handles the setup and thread management. The following shows how to use the MockHttpServer to enumerate and test the expected headers from the client:
private final static int SVR_PORT = 8585;
private final static String SVR_ADDR = "http://localhost:" + SVR_PORT;
...
public void testHeaderEnumerations () throws Exception{
// setup mock server and handler for given path
MockHttpServer server = new MockHttpServer(SVR_PORT);
server.start();
server.addRequestHandler("/test1", new HttpRequestHandler() {
@Override
public void handle(HttpRequest req, HttpResponse rsp, HttpContext context) throws HttpException, IOException {
int headerCount = 0;
String headers = "Accept Accept-Charset";
HeaderIterator it = req.headerIterator();
while (it.hasNext()){
Header h = (Header) it.next();
if(headers.contains(h.getName())){
headerCount++;
}
}
Assert.assertEquals(3, headerCount);
}
});
// setup client connection
URL url = new URL(SVR_ADDR + "/test1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Accept", "text/xml");
conn.addRequestProperty("Accept", "Audio/mpeg");
conn.addRequestProperty("Accept-Charset", "utf-8");
try{
conn.getInputStream();
}finally{
conn.disconnect();
}
server.stop();
}
The top portion of the code sets up the HttpRequestHandler implementation. This is where one specifies how the server would handle the incoming HTTP request. In the implementation above, we are enumerating and validating incoming HTTP headers. The second portion of the code sets up the client call to the MockHttpServer instance. Here, for simplicity, we are using an instance of HttpURLConnection to make the HTTP request to the MockHttpServer.
Link to project - https://github.com/vladimirvivien/workbench/tree/master/android-tutorials/MockHttpServer
About Vladimir Vivien
Vladimir Vivien is a software engineer living in the United States. Past and current experiences include development in Java and C#.Net for industries including publishing, financial, and healthcare. He has a wide range of technology interests including Java, OSGi, Groovy/Grails, JavaFX, SunSPOT, BugLabs, module/component-based development, and anything else that runs on the JVM.
Vladimir is the author of "JavaFX Application Development Cookbook" published by Packt Publishing. He is the creator of the Groovv JmxBuilder open source project, a JMX DSL, that is now part of the Groovy language. Other open source endeavor includes JmxLogger and GenShell. You can follow Vladimir through his blog: http://blog.vladimirvivien.com/, Twitter: http://twitter.com/vladimirvivien, and Linked In: http://www.linkedin.com/in/vvivien.
More About Vladimir »Northern Virginia Software Symposium
November 1 - 3, 2013
Reston, VA
Current Topics on the NFJS Tour
- Core Java, JEE
- Dynamic Languages: Groovy, JRuby, Scala, Clojure
- RESTful Web Apps
- Frameworks: Hibernate, Grails, Spring, JSF, GWT, more
- Agility
- Test Driven Design
- Security
- Ajax, Flex, RIA
Why Attend the NFJS Tour?
- » Cutting-Edge Technologies
- » Agile Practices
- » Peer Exchange
Current Topics:
- Languages on the JVM: Scala, Groovy, Clojure
- Enterprise Java
- Core Java, Java 7
- Agility
- Testing: Geb, Spock, Easyb
- REST
- NoSQL: MongoDB, Cassandra
- Hadoop
- Spring 3
- Automation Tools: Git, Hudson, Sonar
- HTML5, Ajax, jQuery, Usability
- Mobile Applications - iPhone and Android
- More...
NFJS, the Magazine
May Issue Now AvailableOn the road to learning
by Raju GandhiRefactoring to Modularity
by Kirk KnoernschildRESTful Groovy
by Kenneth KousenGetting Started with D3.js
by Brian Sletten