Wednesday, March 17, 2010

Testing all permutations of calls to setters via functional programming

Today i had this class, which has multiple setters and updates bindable properties from the values of these setters. When i wrote a unit test for it, i realized, that i don't know in which order the setters are called. So in principle i had to test all the different orders in which the setters can be called. Al different orders of a list, that's permutations. The class had three setters, which makes for 3! = 6 permutations.

I didn't want to do it manually, so tried to find a way to let the computer do it for me. What i did is to create a function for every call to a setter and a function for the assert. These functions are passed into the assert function like so:


[Test]
public function whenSearchFormIsUsedInStoreContext_thenCountryChooserShouldBeSetToCountryOfTheStore():void
{
storeShortcut.countryCode = country2.code;

var setter1:Function = function():void
{
pm.countriesList = new ArrayCollection([ country0, country1, country2 ]);
};
var setter2:Function = function():void
{
pm.currentContext = RecordsModel.IDENTIFY_CONTEXT_STORE;
};
var setter3:Function = function():void
{
pm.currentStore = storeShortcut;
}
var assert:Function = function(permutation:Array):void
{
assertThat("country2 should be selected, permutation <" + permutation + ">",
pm.selectedCountryIndex,
equalTo(2));
}

assertThatAllPermutationsOfSettersHaveTheSameResult(setUp, [ setter1, setter2, setter3 ],
assert);
}



Now the method can calculate all permutations of the setters array and call the setters accordingly. Works like a charm.

But beware. Faculty is a fast growing function. 7! is 5040 and 8! is 40320. So this method works for a small number of setters only.

No comments:

Post a Comment