Showing posts from 2018

Tip (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 and write a failing 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, Spock thinks it is fine.  It doesn't care about the lines within each block and whether they fail or not.

So we have two choices here:

use .every instead of .each when: List<SomeType> someResults = service.someAction(someParam) then: someResults someResults.every { it.someFieldName == 'so…

Tip: Reverse Sorting 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…