Arrange-Act-Assert vs Given-When-Then

Or: How to structure your tests

Martin Thoma
Plain and Simple

--

Photo by David Travis on Unsplash

Unit tests typically consist of three meaningful phases:

  • Arrange: Set up the preconditions for the tests. That could be creating data/objects or configuring a state.
  • Act: Perform the action that should get tested. Typically this means calling the function/method you want to test
  • Assert: Verify the correctness of the outcome. Typically this means comparing the actual return value with the expected return value, but it could also mean to check Exceptions or log messages.

If you make it explicit, you can call this the AAA pattern. But there are a few other names of patterns you might have seen.

Code using that pattern with pytest (Python) looks like this:

def test_foo():
# Arrange
bar = generate_bar()
baz = generate_baz()

# Act
actual_result = foo(bar, baz)

# Assert
expected_result = "abc"
assert actual_result == expected_result

Please note: If you need to do the same things again and again in the “arrange” step, you can write pytest fixtures.

The Four-phase test pattern

The four-phase pattern is what you might know from JUnit in Java and unittests in…

--

--

Martin Thoma
Plain and Simple

I’m a Software Engineer with over 10 years of Python experience (Backend/ML/AI). Support me via https://martinthoma.medium.com/membership