Category Archives: Articles in English

JsonUnit

Let me introduce you another of my pet projects. It’s called JsonUnit and it’s something like XmlUnit only for JSON (well it’s much, much more simple). Basically it’s able to compare two JSON documents and if they do not match, it prints out the differences. For example the following test

import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;

...

assertJsonEquals("{\n" + 
			"   \"test\":[\n" + 
			"      1,\n" + 
			"      2,\n" + 
			"      {\n" + 
			"         \"child\":{\n" + 
			"            \"value1\":1,\n" + 
			"            \"value2\":true,\n" + 
			"            \"value3\":\"test\",\n" + 
			"            \"value4\":{\n" + 
			"               \"leaf\":5\n" + 
			"            }\n" + 
			"         }\n" + 
			"      }\n" + 
			"   ],\n" + 
			"   \"root2\":false,\n" + 
			"   \"root3\":1\n" + 
			"}", 
			"{\n" + 
			"   \"test\":[\n" + 
			"      5,\n" + 
			"      false,\n" + 
			"      {\n" + 
			"         \"child\":{\n" + 
			"            \"value1\":5,\n" + 
			"            \"value2\":\"true\",\n" + 
			"            \"value3\":\"test\",\n" + 
			"            \"value4\":{\n" + 
			"               \"leaf2\":5\n" + 
			"            }\n" + 
			"         },\n" + 
			"         \"child2\":{\n" + 
			"\n" + 
			"         }\n" + 
			"      }\n" + 
			"   ],\n" + 
			"   \"root4\":\"bar\"\n" + 
			"}");

will result in

java.lang.AssertionError: JSON documents are different:
Different keys found in node "". Expected [root2, root3, test], got [root4, test].
Different value found in node "test[0]". Expected 1, got 5.
Different types found in node "test[1]". Expected NUMBER, got BOOLEAN.
Different keys found in node "test[2]". Expected [child], got [child, child2].
Different value found in node "test[2].child.value1". Expected 1, got 5.
Different types found in node "test[2].child.value2". Expected BOOLEAN, got STRING.
Different keys found in node "test[2].child.value4". Expected [leaf], got [leaf2].

Neat, isn’t it?

Maven, Eclipse, WTP and project dependencies

If you are working with Maven, Eclipse and WTP, you can encounter different problems.

One of them is connected to project dependencies. Imagine that you have an in-house library A and a web application B that depends on A. Sometimes, when I run the webapp in a server using WTP, it can not find classes (or resources) from B. It’s quite confusing if you get a ClassNotFoundException even though the class is apparently there. It happens only if you are using m2eclipse extras. If you have different configuration this solution will not probably help you.

Ok, so you have m2extras and you are getting ClassNotFoundException. What next? You have to check file A/.settings/org.eclipse.wst.common.component (I use the Navigator View to access the file)

If you see something like this

<?xml version="1.0" encoding="UTF-8"?> 
<project-modules id="moduleCoreId" project-version="1.5.0"> 
  <wb-module deploy-name="module-a"> 
  <wb-resource deploy-path="/" source-path="/src"/> 
  </wb-module> 
</project-modules> 

you have found the issue. The source-path attribute is wrong. It’s necessary to set the value to /src/main/java. Sometimes the path is not just wrong, but it’s completely missing. In such case just add a new line with corresponding configuration and everything should work as expected.

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.