This blog will be about capturing network requests made by devices during a test. If we can access network requests from our test code, we could make assertions based on specific requests being sent to our server, or assert that the data in network responses are displayed in the UI.
We can also capture network data to help debug issues when tests fail. We could also make assertions on the performance of our network calls, by checking the timing between requests and responses.

Getting network logs from chrome and safari sessions is relatively easy because the browser debug port makes this information available, but what if we want to capture requests from native applications?
The solution is to use a man-in-the-middle proxy(mitmproxy).  This agent is the program we insert between the device and the Internet. We tell the device to route all requests through our agent, which records the traffic when it passes. It will not only record traffic, but also the agent we will use can be configured to modify traffic. This opens up more potential uses in testing: we can test failure cases when some URLs are inaccessible, and we can modify the response to meet our needs for consistent data.

In this approch we will use mitmproxy-java. A small library which allows convenient access to network requests of devices made in the middle of your test runs.
It has the following features:

  • Starts the proxy server as a background task.
  • Allows for passing in a lambda function which gets called for every intercepted message, allowing you to manage the recording of data any way you see fit.
  • Allows for modifying the responses from the proxy, so you can inject arbitrary data and states into your app.
  • Captures HTTPS traffic even when ip addresses are used instead of host names.

Setup

While mitmproxy-java will start the proxy server for us programmatically, we need to install mitmproxy ourselves:

Copy to Clipboard

Writing Test Using mitmproxy-java

Add the following to your pom file:

Copy to Clipboard

Start mitmproxy:

Copy to Clipboard

Here’s an example of an entire test using mitmproxy-java:

Copy to Clipboard