Using coverage reports for better tests
January 26, 2008 – 2:34 pmAfter creating a Cobertura Plugin for Grails, I thought I’d give it a test run on some simple domain class logic and tests. Consider this example in grails-app/domain:
1 2 3 4 5 6 7 8 9 10 11 12 | class State { String name String postalCode def isMinnesota(){ return 'MN' == postalCode } def isWisconsin(){ return 'WI' == postalCode } } |
The two helper methods (isMinnesota and isWisconsin) deserve some tests:
1 2 3 4 5 6 7 8 9 | void testIsMinnesota() { state.postalCode = 'MN' assertTrue('should be true when state is MN', state.isMinnesota()) } void testIsWisconsin() { state.postalCode = 'WI' assertTrue('should be true when state is WI', state.isWisconsin()) } |
Looks good, right? When I run grails test-app-coverage and look at the reports, there is 100% line coverage, but the branch coverage is only 50%:

The tests didn’t take into account the case in which the state is NOT Minnesota or NOT Wisconsin. Just modify the test cases to add some assertions:
1 2 3 4 5 6 7 8 9 10 11 12 13 | void testIsMinnesota() { state.postalCode = 'NOT mn' assertFalse('should be false when state is not MN', state.isMinnesota()) state.postalCode = 'MN' assertTrue('should be true when state is MN', state.isMinnesota()) } void testIsWisconsin() { state.postalCode = 'NOT wi' assertFalse('should be false when state is not WI', state.isWisconsin()) state.postalCode = 'WI' assertTrue('should be true when state is WI', state.isWisconsin()) } |
And run the reports again:

And now there’s 100% line coverage AND 100% branch coverage – perfect.

Sorry, comments for this entry are closed at this time.