Showing posts from August, 2018

QuickTip (Spock): Don't use .each in a then block!!!

This happens time and time again. QA finds a bug and I swear I wrote a test for that condition. So, I go back to try to debug that test.  I see the original test I wrote and the condition that should fail.  It looks something like this:

when: List<SomeType> someResults = service.someAction(someParam) then: someResults // assert the result is not null, empty list, etc someResults.each { it.someFieldName == 'someValue' it.someOtherFieldName == 1 }
In this case, someOtherFieldName is empty but the test still passes... wtf?! right?

Well, this is actually the expected behavior.

Because each doesn't actually return anything from the closure but just returns the collection itself, Spock thinks it is fine.  It doesn't care about the lines within the each block and whether they fail or not.

So we have a few choices here:
use .every (only applies to the last line) when: List<SomeType> someResults = service.someAction(someParam) th…

QuickTip: Reversing Sort Order in Groovy

One of the great things about Groovy is that there are multiple ways to get **it done. This means people learning Groovy and especially those coming from other programming languages can use the same syntax and practices they are already familiar with. However, this may result in some small mistakes or inefficiencies.

The first one I want to highlight today is reverse sorting.

So given:

class Person { String name Integer age }
If we want to sort a list of people by their age, we would normally use:

people.sort { it.age }
To reverse the list, we have several options including:

people.sort { it.age }.reverse()

people.sort { -it.age }
The first one, I see a lot. It's easy to write and to think about, but it's not as efficient as the second one. Why sort the list and then reverse it, when you can sort by the criteria you want in the first place?

The next problem comes with the '-' notation. It works great for examples like this when we are sorti…