# The MustCreate Pattern for Go Tests

DevFeed: [The MustCreate Pattern for Go Tests](<https://devfeed.tech/articles/the-mustcreate-pattern-for-go-tests-122086.md>)

Original publisher: [Read original article](<https://mtlynch.io/notes/go-must-create-pattern/>)

Author: Michael Lynch

Published: 2026-11-06T00:00:00Z

Content type: article

Language: en

Sources: [Mtlynch](<https://devfeed.tech/sources/mtlynch-io.md>)

Topics: [Boilerplate](<https://devfeed.tech/topics/boilerplate.md>), [Test-driven development](<https://devfeed.tech/topics/tdd.md>), [Error Handling](<https://devfeed.tech/topics/error-handling.md>)

Tags: [constructor](<https://devfeed.tech/tags/constructor.md>), [error](<https://devfeed.tech/tags/error.md>), [function](<https://devfeed.tech/tags/function.md>), [generic](<https://devfeed.tech/tags/generic.md>), [generics](<https://devfeed.tech/tags/generics.md>), [go](<https://devfeed.tech/tags/go.md>), [pattern](<https://devfeed.tech/tags/pattern.md>), [tests](<https://devfeed.tech/tags/tests.md>)

## AI overview

For Go tests, a generic `MustCreate` helper can reduce repeated error-checking and avoid a separate `MustCreateX` helper for each type. It accepts `testing.TB`, a one-argument constructor returning `(value, error)`, and raw input; it marks itself with `t.Helper()`, fails the test if construction returns an error, and returns the value otherwise. Go infers the input and output types from the constructor. For constructors with two arguments, the excerpt adds a parallel `MustCreate2` helper with a second input type and parameter. The examples use values expected to be valid, but the helpers still fail the test if construction fails.

## Source excerpt

I recently discovered a handy way to make Go tests more readable and less repetitive. Suppose I have a constructor that can fail: func NewUsername(raw string) (Username, error) { ... } And I have another function that takes a Username as an argument: func (ds Datastore) ReadUser(username Username) (User, error) { ... } When I write tests for ReadUser, I call NewUsername with a value I know is valid, but I still have to include a lot of verbose error-checking code to convince the compiler that everything is okay: