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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • JUnit 5 Custom TestListeners
  • Integrate Cucumber in Playwright With Java

Trending

  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introduction to Retrieval Augmented Generation (RAG)
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  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 user avatar
Gabriel Deliu
·
Updated Dec. 29, 16 · Opinion
Likes (19)
Comment
Save
Tweet
Share
31.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • JUnit 5 Custom TestListeners
  • Integrate Cucumber in Playwright With Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!