Tag Archives: Mock

Mock socket

Few months ago I have written a small tool that mocks network sockets in Java. Now I have some time to describe it, so here you are.

Let’s imagine you want to test network communication in Java. It’s not easy, you have to start some server on the other side, configure its responses and somehow verify that the data you send are correct.

With mock-socket it’s incredibly easy.

import static net.javacrumbs.mocksocket.MockSocket.*;
...

//prepare mock
byte[] dataToWrite = new byte[]{5,4,3,2};
expectCall().andReturn(emptyResponse());
	
//do test
Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
IOUtils.write(dataToWrite, socket.getOutputStream());
socket.close();
	
//verify data sent
assertThat(recordedConnections().get(0), data(is(dataToWrite)));
assertThat(recordedConnections().get(0), address(is("example.org:1234")));

You see, just statically import MockSocket class, prepare the mock, execute the test and verify the data. The library just removes the default Java socket implementation and place a mock implementation in its stead.

Of course, this example does not have much sense. It just tests that Java socket implementation works. But imagine that you implement some non-trivial network library. A test library can be handy.

Moreover, there is a HTTP extension which can be used if you want to test some HTTP client. Let’s say a JSON REST client. In such case, you can write this.

import static net.javacrumbs.mocksocket.http.HttpMockSocket.*;

...

//prepare mock
expectCall()
  .andWhenRequest(uri(is("/test/something.do")))
     .thenReturn(response().withStatus(404))
  .andWhenRequest(uri(is("/test/other.do")))
    .thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text"));

//do your test
...

//verify 
assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));		

Ain’t great? You can do much more, please take a look at the project page if you are interested.