Fill Go test structs with fake data
Declare a struct, tag each field with fake:"…", and FakeStruct fills it. A seed and a date make a test get the same values on every run.
You need the library in your Go module: go get github.com/larvit/fejkdata@v0.8.0, the release this page is written for.
1. Tag the fields
A tag binds a draw with as, such as {/sv_SE.sex as s}, and the other tags read that draw in any field order, so the fields agree: the first name matches the sex, and the personnummer spells that sex. {seq()} counts the structs from 1.
2. Fix the seed and the date
WithSeed and WithToday are both required. The same seed and the same date give the same customer on every run of one fejkdata version, because ages, and so personnummer, count from the date. Pass time.Now() to WithToday only where the test doesn't compare values.
3. The test
Save this as signup_test.go. With fejkdata v0.8.0 it passes:
package signup
import (
"testing"
"time"
"github.com/larvit/fejkdata"
svse "github.com/larvit/fejkdata/data/sv_SE"
)
type Customer struct {
ID int64 `fake:"{seq()}"`
Sex string `fake:"{/sv_SE.sex as s}{s.name}"`
First string `fake:"{s.first-name}"`
Last string `fake:"{/sv_SE.last-name as l}{l}"`
Personnummer string `fake:"{s.personnummer}"`
Email string `fake:"{slugify(s.first-name)}.{slugify(l)}@example.com"`
}
// newFejkdata gives the same customers on every run: one seed, and one date to count ages from.
func newFejkdata(t *testing.T) *fejkdata.Generator {
t.Helper()
day := time.Date(2026, 11, 21, 0, 0, 0, 0, time.UTC)
f, err := fejkdata.New(fejkdata.WithDataFS(svse.Modules()...), fejkdata.WithSeed(1), fejkdata.WithToday(day))
if err != nil {
t.Fatal(err)
}
return f
}
func TestCustomer(t *testing.T) {
var c Customer
if err := newFejkdata(t).FakeStruct(&c); err != nil {
t.Fatal(err)
}
want := Customer{
ID: 1,
Sex: "kvinna",
First: "Viktoria",
Last: "Larsson",
Personnummer: "940623-2380",
Email: "viktoria.larsson@example.com",
}
if c != want {
t.Errorf("got %+v, want %+v", c, want)
}
}
func TestTheSameOnEveryRun(t *testing.T) {
var first, second Customer
if err := newFejkdata(t).FakeStruct(&first); err != nil {
t.Fatal(err)
}
if err := newFejkdata(t).FakeStruct(&second); err != nil {
t.Fatal(err)
}
if first != second {
t.Errorf("two generators with one seed and one date drew %+v and %+v", first, second)
}
}
More: Go tests, the library and Names, which explains as.