1. Introduction

When writing tests we often assert comparisons on various attributes of an object. Spock has some useful language features that help us eliminate duplication when we compare objects.

In this tutorial, we’ll learn how to refactor our tests using Spock’s Helper Methods, with() and verifyAll(), to make our tests more readable.

2. Setup

First, let’s create an Account class with a name, a current balance, and an overdraft limit:

public class Account {
    private String accountName;
    private BigDecimal currentBalance;
    private long overdraftLimit;

    // getters and setters
}

3. Our Basic Test

Now let’s create an AccountTest Specification with a test that verifies our getters and setters for account name, current balance, and overdraft limit. We’ll declare the Account as our @Subject and create a new account for each test:

class AccountTest extends Specification {
    @Subject
    Account account = new Account()

    def "given an account when we set its attributes then we get the same values back"() {
        when: "we set attributes on our account"
        account.setAccountName("My Account")
        account.setCurrentBalance(BigDecimal.TEN)
        account.setOverdraftLimit(0)

        then: "the values we retrieve match the ones that we set"
        account.getAccountName() == "My Account"
        account.getCurrentBalance() == BigDecimal.TEN
        account.getOverdraftLimit() == 0
    }
}

Here, we’ve repeatedly referenced our account object in our expectations. The more attributes we have to compare, the more repetition we need.

4. Refactoring Options

Let’s refactor our code to remove some of this duplication.

4.1. Assertion Traps

Our initial attempt might extract the getter comparisons into a separate method:

void verifyAccount(Account accountToVerify) {
    accountToVerify.getAccountName() == "My Account"
    accountToVerify.getCurrentBalance() == BigDecimal.TEN
    accountToVerify.getOverdraftLimit() == 0
}

But, there’s a problem with this. Let’s see what it is by creating a verifyAccountRefactoringTrap method to compare our account but use the values from someone else’s account:

void verifyAccountRefactoringTrap(Account accountToVerify) {
    accountToVerify.getAccountName() == "Someone else's account"
    accountToVerify.getCurrentBalance() == BigDecimal.ZERO
    accountToVerify.getOverdraftLimit() == 9999
}

Now, let’s invoke our method in our then block:

then: "the values we retrieve match the ones that we set"
verifyAccountRefactoringTrap(account)

When we run our test, it passes even though the values don’t match! So, what’s going on?

Although the code looked like it was comparing the values, our verifyAccountRefactoringTrap method contains boolean expressions but no assertions!

Spock’s implicit assertions only occur when we use them in the test method, not from inside called methods.

So, how do we fix it?

4.2. Assert Inside Methods

When we move our comparisons into a separate method, Spock can no longer enforce them automatically, so we must add the assert keyword ourselves.

So, let’s create a verifyAccountAsserted method that asserts our original account values:

void verifyAccountAsserted(Account accountToVerify) {
    assert accountToVerify.getAccountName() == "My Account"
    assert accountToVerify.getCurrentBalance() == BigDecimal.TEN
    assert accountToVerify.getOverdraftLimit() == 0
}

And let’s call our verifyAccountAsserted method in our then block:

then: "the values we retrieve match the ones that we set"
verifyAccountAsserted(account)

When we run our test it still passes and when we change one of the asserted values it will fail just like we expect.

4.3. Return a Boolean

Another way we can ensure our method is treated as an assertion is to return a boolean result. Let’s combine our assertions with the boolean and operator, knowing that Groovy will return the result of the last executed statement in the method:

boolean matchesAccount(Account accountToVerify) {
    accountToVerify.getAccountName() == "My Account"
      && accountToVerify.getCurrentBalance() == BigDecimal.TEN
      && accountToVerify.getOverdraftLimit() == 0
}

Our test passes when all conditions match and fails when one or more don’t, but there’s a drawback. When our test fails, we won’t know which of our three conditions wasn’t met.

Although we can use these approaches to refactor our test, Spock’s helper methods give us a better approach.

5. Helper Methods

Spock provides two helper methods “with” and “verifyAll” that help us solve our problem more elegantly! Both work in much the same way, so let’s start by learning how to use with.

5.1. The with() Helper Method

Spock’s with() helper method takes an object and a closure for that object. *When we pass an object to the helper method with(), our object’s attributes and methods are added to our context. This means we don’t need to prefix them with the object name when we’re inside the scope of our with() closure.*

So, one option is to refactor our method to use with:

void verifyAccountWith(Account accountToVerify) {
    with(accountToVerify) {
        getAccountName() == "My Account"
        getCurrentBalance() == BigDecimal.TEN
        getOverdraftLimit() == 0
    }
}

*Notice that power assertions apply inside Spock’s helper method, so we don’t need any asserts even though it’s in a separate method!*

Usually, we don’t even need a separate method, so let’s use with() directly in the expectations of our test:

then: "the values we retrieve match the ones that we set"
with(account) {
    getAccountName() == "My Account"
    getCurrentBalance() == BigDecimal.TEN
    getOverdraftLimit() == 0
}

And now let’s invoke our method from our assertions:

then: "the values we retrieve match the ones that we set"
verifyAccountWith(account)

Our with() method passes but fails a test on the first comparison that doesn’t match.

5.2. With for Mocks

We can also use with when asserting interactions. Let’s create a Mock Account and invoke some of its setters:

given: 'a mock account'
Account mockAccount = Mock()

when: "we invoke its setters"
mockAccount.setAccountName("A Name")
mockAccount.setOverdraftLimit(0)

Notice that we can omit mockAccount when verifying mockAccount.setAccountName as it’s in our with‘s scope.

5.3. The verifyAll() Helper Method

Sometimes we’d rather know every assertion that fails when we run our test. In this case, we can use Spock’s verifyAll() helper method, in the same way that we used with.

So, let’s add a check using verifyAll():

verifyAll(accountToVerify) {
    getAccountName() == "My Account"
    getCurrentBalance() == BigDecimal.TEN
    getOverdraftLimit() == 0
}

Instead of failing a test when one comparison fails, the verifyAll() method will continue executing and report all failing comparisons inside verifyAll’s scope.

5.4. Nested Helper Methods

When we have an object within an object to compare we can nest our helper methods.

To see how let’s first create an Address with a street and a city and add it to our Account:

public class Address {
    String street;
    String city;

    // getters and setters
}
public class Account {
    private Address address;

    // getter and setter and rest of class
}

Now that we have an Address class, let’s create one in our test:

given: "an address"
Address myAddress = new Address()
def myStreet = "1, The Place"
def myCity = "My City"
myAddress.setStreet(myStreet)
myAddress.setCity(myCity)

And add it to our account:

when: "we set attributes on our account"
account.setAddress(myAddress)
account.setAccountName("My Account")

Next, let’s compare our address. When we don’t use helper methods, our most basic approach is:

account.getAddress().getStreet() == myStreet
account.getAddress().getCity() == myCity

We could improve this when by extracting an address variable:

def address = account.getAddress()
address.getCity() == myCity
address.getStreet() == myStreet

But better still, let’s use the with helper method for a cleaner comparison:

with(account.getAddress()) {
    getStreet() == myStreet
    getCity() == myCity
}

Now that we’re using with to compare our address, let’s nest it within our comparison of the Account. Since with(account) brings our account into scope, we can drop it from account.getAddress() and use with(getAddress()) instead:

then: "the values we retrieve match the ones that we set"
with(account) {
    getAccountName() == "My Account"
    with(getAddress()) {
        getStreet() == myStreet
        getCity() == myCity
    }
}

Since Groovy can derive getters and setters for us, we can also refer to our object’s properties by name.

So, let’s make our test yet more readable by using the property names rather than getters:

with(account) {
    accountName == "My Account"
    with(address) {
        street == myStreet
        city == myCity
    }
}

6. How Do They Work?

We’ve learned how with() and verifyAll() help us to make our tests more readable, but how do they do that?

Let’s look at the method signature for with():

with(Object, Closure)

So we can use with() by passing it a Closure as the second argument:

with(account, (acct) -> {
    acct.getAccountName() == "My Account"
    acct.getOverdraftLimit() == 0
})

But Groovy has special support for methods where the last argument is a Closure. It allows us to declare the Closure outside of the parenthesis.

So, let’s use Groovy’s more readable equivalent, but more succinct form:

with(account) {
    getAccountName() == "My Account"
    getOverdraftLimit() == 0
}

Notice that there are two arguments yet in our tests we only passed one argument, account, to with().

The second, Closure, argument is the code within the curly braces immediately after our with, which gets passed the first, account, argument to operate on.

7. Conclusion

In this tutorial, we learned how to use Spock’s with() and verifyAll() helper methods to reduce the boilerplate in our tests when we compare objects. We learned how helper methods can be used for simple objects, and nested when our objects are more complex. We also saw how to use Groovy’s property notation to make our helper assertions even cleaner and how to use helper methods with Mocks. Finally, we learned how we gain from Groovy’s alternative, cleaner, syntax for methods whose last parameter is a Closure when using helper methods.

As usual, the source for this tutorial is over on GitHub.