QuickTip (Spock): Remember to add asserts when creating helper methods in spock tests

This is very similar to my blog post about using .each in Spock tests.

The Problem

Having helper methods in a large spec is generally a good practice. For example, we use this pattern a lot is in testing lists of results.

 def 'test that does some stuff'() {
    given:
    String someFieldName = 'someOtherValue' 

    when:
    List<SomeType> someResults = service.someAction(someParam)

    then:  
    someResults.each {
       assertResultContainsAllTheseThings(it)
    }
 }

 .
 .
 .

 private boolean assertResultContainsAllTheseThings(SomeType result) {
   result.someFieldName == 'someValue'
   result.someOtherField == 'someOtherThing'
   result.someList.size() == 3
 }

I've run into lots of problems with tests not failing when they should have because I forgot to do this.

The Solution

If you can already tell what's wrong with this code, congrats! If you can't, when copy pasting that original check from the then block into a helper method, don't forget to add the asserts!

 private boolean assertResultContainsAllTheseThings(SomeType result) {
   assert result.someFieldName == 'someValue'
   assert result.someOtherField == 'someOtherThing'
   assert result.someList.size() == 3
 }

or use the 'with' method.

 private void assertResultContainsAllTheseThings(SomeType result) {
   with(result) {
      someFieldName == 'someValue'
      someOtherField == 'someOtherThing'
      someList.size() == 3
   }
 }

Conclusion

Take a look at your test suites today and see if you have any of these in your codebase.

Comments

Post a Comment