Embedding TcpMon within test units

TcpMonitor is a well-known sub-project of Apache WebServices Commons. It provides a proxy allowing to display the content of HTTP requests and responses. You probably use its Swing user interface but do you know that it can also be used within Java code?

This possibility allows embedding proxy within your unit tests and have everything launched in same time. It actually makes possible to start out your HTTP server, plug your proxy in front of it and execute calls from the client. With this approach, you will be able to display HTTP content…

The jar file of version 1.0 of TcpMon doesn’t allow to do that so we need to get the source code from the trunk and build it. The project uses Maven, has a root Maven project and is structured using modules. In our case, the module that we are interested in is the tcpmon-core one.

Now this is done, you can configure the TcpMon’s proxy from our unit test content as described below:

InterceptorConfigurationBuilder builder = new InterceptorConfigurationBuilder();
InterceptorConfiguration configuration = builder.build();

Interceptor interceptor = new Interceptor(config, new Dump(System.out));

After having configured proxy information, we actually start it using the Interceptor class. The content of HTTP requests and responses can be obtain then though the Dump class. We can obviouly provide our own OutputStream to get content and parse it…

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Interceptor interceptor = new Interceptor(config, new Dump(baos));

//Actually execute call

String content = baos.toString();
System.out.println("content = "+content);

For information, the content contains both HTTP request and response content.

This entry was posted in Java. Bookmark the permalink.

2 Responses to Embedding TcpMon within test units

  1. Michael says:

    I like what you’re saying – its a very good idea.
    Could you explain why the ‘interceptor’ obj is reinstanciated in your example (1st time before the Thread.sleep(), 2nd after the baos is declared) ?

    • templth says:

      In fact, it’s two separate samples… One with the standard output (System.out) and one with your output stream (ByteArrayOutputStream in this case).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s