Go Unit Test Naming Conventions
You're working on a Go project (yay! 🎉) and you need to write a unit
test. You decide to go with a table-driven approach. What names should
you use for your variables?
For a long while, I was writing
tests using names like these:
func TestSomething(t *testing.T) { scenarios := []struct { description string arg string expected string }{ { description: "Thing 1", arg: "this", expected: "that" } // more cases go here } for _, scenario := range scenarios { t.Run(scenario.description, func(t *testing.T) { // ... } } }
The cases are "scenarios" and they are to produce "expected" values.
This was coming from a world of Java and JUnit, where these naming
conventions were wildly use (well, I can't remember if they were
wildly use, but that's what I called them).
After a
while, working with other Go developers, I learnt a convention that's a
little more "Go" like:
func TestSomething(t *testing.T) { tests := []struct { description string arg string want string }{ { description: "Thing 1", arg: "this", want: "that" } // more cases go here } for _, tt := range tests { t.Run(scenario.description, func(t *testing.T) { // ... } } }
Note the use of test
, tt
, and want
. Not only were these the terms
I see other devs use, my IDE auto-expands to these terms when I start
working on a unit test, so I can only attribute to them being the
convention. You can probably make a case for description
being desc
given Go's preference for short variable names.
Of course,
I'm not saying you have to use these: you do you. But these are the
names I think I'll adopt.