Service layer woes

July 18, 2007

I have posted an entry on the blog of my employer:

http://blog.xebia.com/2007/07/18/service-layer-woes/

Advertisements

Test Refactoring: extract an assert

July 8, 2007

When writing unit tests, I often see large sections of repeated asserts and asserts that are too low level:

void testAdd(){
	List list = new LinkedList();

	String s = "foo";
	list.add(s);

	assertEquals(1,list.size());
	assertEquals(s,list.get(0));
}

In this case the asserts are checking that the list contains the added item. This is done based on checking the size and checking of elements. The problem is that this logic often is repeated all over the place.

The smell can be removed by extracting an assert that spans the conceptual distance: it states what it does, but it doesn’t say how it does the job (extract method):

void testAdd(){
	List list = new LinkedList();

	String s = "foo";
	list.add(s);

	assertListContent(list,s);
}

void assertListContent(List list, Object... args){
	List expectedList = asList(args);
	assertEquals(expectedList,list);
}

This code can even be simplified by making List a member variable of the TestCase:

void testAdd(){
	list = new LinkedList();

	String s = "foo";
	list.add(s);

	assertListContent(s);
}

void assertListContent(Object... args){
	List expectedList = asList(args);
	assertEquals(expectedList,list);
}

It doesn’t look like it is adding much value, but I have seen enough unnecessary difficult to understand tests because of too many low level asserts. And when test are hard to understand, they are also hard to maintain. That is why I like my test methods short and clear (10/15 lines normally).