from Hacker News

How I write unit tests in Go

by badrequest on 4/10/24, 3:49 PM with 27 comments

  • by kbolino on 4/11/24, 1:02 PM

    For table-based testing, I have been using map[string]struct{...} for a while now instead of including the test name as a struct field. I have found it improves readability slightly and makes it harder to misname test cases (empty strings stand out more and duplicates won't compile).

    Also, the shadowing of t in t.Run is intentional. You should not try to work around it. There's no risk of confusion either because you will always use the right one in the right place.

  • by ashconnor on 4/11/24, 4:33 AM

    I'm far too lazy to write mocks by hand in go. You can generate a mock for a given interface with mockery https://github.com/vektra/mockery
  • by coffeebeqn on 4/11/24, 1:38 AM

    So unless I pepper every test and subtest with t.Parallel() it will always run sequentially ? I gotta try that. Also I wish I could just declare that once
  • by tommiegannert on 4/11/24, 7:10 AM

    Nice showdown of a bunch of scenarios.

    I'd add using testing.T.Cleanup for tearing down the testcontainer (or use a TestMain and a deferred if the container is slow and concurrency-safe.)

  • by count_chocula on 4/12/24, 10:36 PM

    i am terrified of clicking on that website link
  • by jozvolskyef on 4/10/24, 8:36 PM

    I would vote this down if I could for the following reasons:

    - I prefer state-based TDD as opposed to interaction-based (see https://martinfowler.com/articles/mocksArentStubs.html).

    - I've used both testcontainers and dockertest, and from my experience dockertest is more robust.

    - The capital T for the outer argument comes across as being hypercorrect. Why would one consider the shadowing of this argument bad?