Can we build it? Yes, we can!!!

When writing test cases, we construct supporting objects in order to simulate different test scenarios. These supporting objects are configured slightly differently in each scenario. Creating these objects can be quite an involved task. One common approach we find in our code base is to have different “creation methods” to configure these objects.

We can be easily be overwhelmed by the number of creation methods, and the parameters we have to pass into each one.

public void testCellPhoneIsSilent() {
    CellPhone phone = createCellPhone(true, true, true, 5, 2, 1, 2);
    ...
}

To understand what kind of cell phone is being created, one must understand what each parameter means. Using such creation methods leads to tests that are harder to read and perhaps more difficult to maintain.

We can increase the readability by introducing a “mini internal domain specific language”.

public void testCellPhoneIsSilent() {
    CellPhone phone = cellPhoneBuilder()
    				.silent()
    				.vibrate()
    				.callDisplayOn()
    				.numberRingsBeforeVoiceMail(5)
    				.ringerVolumeLevel(2)
    				.speakerVolumeLevel(1)
    				.displayContrast(2)
    				.build();
    ...
}

Here, the cellPhoneBuilder acts as a “configurer” with more “readable” methods.

Perhaps this is one advantage that a DSL has over an API.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply