The "ClassThat" Naming Convention
Wednesday, 22. July 2009, 20:25:59
I have noticed a pattern in my unit-testing recently. Ah, the word "pattern" is possibly a tad loaded for this purpose, so you might also call it a trend, a style or a convention. It's a recurring thing anyways, and it has to do with how I build my mock objects in my unit tests. I write primarily in Java, by the way, so this is where I noticed this pattern but it may just as well apply, with or without modification, to other languages.
Onwards.
The gist of it that if I have some class called a "Peg" that is used in all sorts of situations throughout my code and I need to build mocks of it for testing, then I will create a companion class called "PegThat" in the test sources tree.
This "PegThat" class will consist of nothing but static methods that all return various forms and instances of Pegs. These static methods will have names telling of certain properties of the Pegs they return. For instance, it might have an "isSquare" method that returns a square Peg.
The beauty of this naming convention is the readability that ensures in my test code. Behold:
That is arguable a very contrived example, but when you are building more complex mocks or instances, and these static methods need parameters or various types, then the benefit increases. Your tests can become a lot less messy and a good deal more readable.
Onwards.
The gist of it that if I have some class called a "Peg" that is used in all sorts of situations throughout my code and I need to build mocks of it for testing, then I will create a companion class called "PegThat" in the test sources tree.
This "PegThat" class will consist of nothing but static methods that all return various forms and instances of Pegs. These static methods will have names telling of certain properties of the Pegs they return. For instance, it might have an "isSquare" method that returns a square Peg.
The beauty of this naming convention is the readability that ensures in my test code. Behold:
@Test public void
squarePegsMustFitIntoSquareHoles() {
Peg peg = PegThat.isSquare();
Hole hole = HoleThat.hasEdges(4);
assertThat(peg, fitsInto(hole));
}
That is arguable a very contrived example, but when you are building more complex mocks or instances, and these static methods need parameters or various types, then the benefit increases. Your tests can become a lot less messy and a good deal more readable.



How to use Quote function: