DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Top 7 Mistakes When Testing JavaFX Applications

Trending

  • Avoiding AI Debt as a Team
  • The Three Tiers of Agentic Incident Response: When to Trust AI Autonomy
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. A Functional Approach to Given When Then Using Java 8

A Functional Approach to Given When Then Using Java 8

A couple of months ago, while working on a new project, I started to look for an easy way to have this Given-When-Then separation in my tests.

By 
Gabriel Deliu
·
Updated Dec. 29, 16 · Opinion
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
32.3K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The Given-When-Then story

Given-When-Then started out as a pattern for writing tests, notably with BDD. The idea is to split the test into three parts:

  1. Given: The initial context is received.

  2. When: One or more actions are performed.

  3. Then: The action results are checked against expectations.

Several testing frameworks have used this approach for writing tests. One of these is Cucumber, where the test is written using human-readable sentences and the coding is done behind the scenes by implementing a fixture for each test step.  A very basic test would look like this:

Given a valid account
When you log in
Then you should see the dashboard

Usage in Code

At some point, some developers started to split their test implementations into the three Given-When-Then parts.

Some used comments:

@Test
public void regularUserShouldSeeDashboardWhenLoggedIn() {
    //Given
    User regularUser = new RegularUser("John");

    //When
    Application.login(regularUser);

    //Then
    assertTrue("dashboard should be visible", ApplicationSpy.isDashboardVisible());
}

And some used labels:

@Test
public void regularUserShouldSeeDashboardWhenLoggedIn() {
    Given:
    User regularUser = new RegularUser("John");

    When:
    Application.login(regularUser);

    Then:
    assertTrue("dashboard should be visible", ApplicationSpy.isDashboardVisible());
}

This separation makes the test easier to read no matter which of the above options you choose.

Richard Warburton wrote an article where he explored other ways to use labels for the Given-When-Then code separation.

A functional approach to Given When Then using Java 8

A couple of months ago, while working on a new project, I started to look for an easy way to have this Given-When-Then separation in my tests. This was a Java 8 project and I was sure that there was a new way of doing this using lambdas.

To my surprise, I didn't find anything revolutionary, so I decided to give 15 minutes to the crazy idea of doing something myself.

If you think about it, you should see that there is a chain in Given-When-Then. This is because values are passed from one step to the other:

  1. Given receives the context and passes it to When.

  2. When receives the context, performs one or more actions, and passes the result to Then.

  3. Then receives the result and checks it against the expectations.

So, then, why wouldn't we use chaining functions to represent the Given-When-Then parts in our code?

And so, using a bit of lambda magic, this has been made to work:

@Test
public void regularUserShouldSeeDashboardWhenLoggedIn() {
  given("a regular user", new RegularUser("John"))
    .when("logging in", regularUser -> Application.login(regularUser).getSpy())
    .then("dashboard should be visible", applicationSpy -> applicationSpy.isDashboardVisible());
}

The solution has been made public. Here is the GitHub Java 8 project.

The equivalent JavaScript solution was much easier to develop:

it('should display the dashboard when a regular user logs in', () => {
  given(getNewRegularUser())
    .when(regularUser => performLogin(regularUser).getSpy())
    .then(applicationSpy => applicationSpy.isDashboardVisible());
});

The JavaScript GitHub project can be found here.

Conclusion

This is just another way of doing the Given-When-Then separation in code. It works for me but it might not be the right choice for someone else. However, I think it's always nice to have options.

I would like to thank S&T for allowing the GitHub projects to start.

If you have any thoughts, please feel free to comment. Thank you!

Java (programming language) Testing

Published at DZone with permission of Gabriel Deliu. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Top 7 Mistakes When Testing JavaFX Applications

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook