Test-With-Expect: A BDD-style Go naming pattern

Sindre Myren
Makes Sense
Published in
2 min readJun 10, 2020

--

In the full article published on the dev.to platform, I explore how we can write GWT-inspired tests in Go without a DSL or test-framework. It’s rather long, so here is a short summary for the inpatient reader.

Did you know that you could write GWT-style (Given-When-Then) tests in Go without a DSL like the ones offered by Gonvey or Ginko?

GWT-Style tests

All you need to do, is to use Go subtests:

GWT-style tests relying on Go subtests (t.Run) and using searis/subtest as a matcher.

In Searis, we have been doing this for a while. There is one very noticable problem though; it generate long and unreadable test names.

TestSum/Given_a_non-empty_int-slice_S/When_calling_Sum(S)/Then_it_should_not_fail
TestSum/Given_a_non-empty_int-slice_S/When_calling_Sum(S)/Then_it_should_return_the_correct_sum
TestSum/Given_a_non-empty_int-slice_S/When_calling_Sum(S)/Then_S_should_be_unchanged
TestSum/Given_an_empty_int-slice_S/When_calling_Sum(S)/Then_it_should_not_fail
TestSum/Given_an_empty_int-slice_S/When_calling_Sum(S)/Then_it_should_return_zero
TestSum/Given_an_empty_int-slice_S/When_calling_Sum(S)/Then_S_should_be_unchanged

Maybe we could use a different wording and simpler language to make the test-names more precise and easier to scan?

TWE-Style tests

In the orginal article, we ended up with the wording Test-With-Expect, or TWE for short:

- Test: Type or function to test (subject).
- With: Configuration or input that are some-how passed to subject (configuration)
- Expect: What to expect afterwards (check).

By applying different wording and enforcing a simpler language, the code ends up sligthly shorter.

And the test names end up significantly shorter:

TestSum/With_non-empty_int_slice/Expect_no_error
TestSum/With_non-empty_int_slice/Expect_correct_sum
TestSum/With_non-empty_int_slice/Expect_input_is_unchanged
TestSum/With_empty_int_slice/Expect_no_error
TestSum/With_empty_int_slice/Expect_zero
TestSum/With_empty_int_slice/Expect_input_is_unchanged

Short names are an important idiom in Go, and test-names are also names.

Summing it up

That’s all. Be sure to read the full article if you are interested in some more motivation and reasoning around the pattern.

--

--

Sindre Myren
Makes Sense

Backend developer at Searis AS, and occasional tech blogger.