Mocked HTTP Server for Android App Testing

It’s pretty hard to mock a real web server. We had met the same issue while testing WikiCards. Finally, we decided to include a small web server as our testing server. We tests our app with pre-hooking request handlers to sending expected or unexpected data to our app. This post states how we do it.

The Web Server – NanoHttpd

NanoHttpd is one of the tiny web server we can use in our project. But we may want to run it in Android environment. So, the best choice should be NanoHttpd. We download it from their After downloaded, we need to use maven to build it.

If you need a pre-build version, you may find it in our repo:


Prepare NanoHttpd for Test Case

We wrote a SimpleWebServer which extends NanoHTTPD class for our test cases. You may find the source code here. It responses the pre-defined Response object according to the pre-defined requested URI. And the code is really simple:


Use SimpleWebServer in Test Case

We uses SimpleWebServer for the test our DownloadService, DownloadServiceTest. We map /a to our pre-defined responses which has OK 200 and Not Found 404 cases. While creating SimpleWebServer, we uses 8088 as our port of web server. We should also use port 80 as our web server. But it may be too risky to use standard web server port in test case. If we want to add a web server for our app, we may have port confliction. So, we just use 8088 to prevent it. The code looks like:


The featured image is downloaded from which is a free image.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *