Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on the LambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

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)

Now let’s verify some interactions using with applied to our mockAccount:

with(mockAccount) {
    1 * setAccountName(_ as String)
    1 * setOverdraftLimit(_)
}

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)