GeistHaus
log in · sign up

if got, want: A Simple Way to Write Better Go Tests

mtlynch.io

There’s an excellent Go testing pattern that too few people know. I can teach it to you in 30 seconds. Instead of writing Go tests like this: // The common, unrefined way. username := GetUser() if username != "dummyUser" { t.Errorf("unexpected username: got %s, want: %s", username, "dummyUser") } Write your tests like this, beginning each assertion with if got, want :=: // The underused, elegant way. if got, want := GetUser(), "dummyUser"; got != want { t.Errorf("username=%s, want=%s", got, want) } The if got, want :=: pattern works even better in table-driven tests. Here’s an example from my library for parsing social media handles:

1 page links to this URL
How to Write Blog Posts that Developers Read

Software bloggers can make the same mistakes for years that prevent readers from discovering their writing. I know because I'm one of them. Over time, I've learned techniques that help some blog posts succeed and the pitfalls that cause others to languish in obscurity.

137 inbound links article en