Generating Fake Data for Testing in Go with GoFakeIt

Generating Fake Data for Testing in Go with GoFakeIt

Say Goodbye to Hand-Written Mocks

When writing tests, sample data is essential. But manually mocking up data for every test is tiring and messy. That's where the GoFakeIt Go library comes in handy!

In this post, we'll explore how GoFakeIt can effortlessly generate realistic fake data to fuel your tests.

Why Use a Mock Data Library?

Mock data is crucial for writing robust unit and integration tests:

  • Allows testing logic and behavior independently from databases and services.

  • Avoids polluting your dev environment with fake data.

  • Data can be randomly generated for complete coverage.

  • Speeds up test execution since no dependencies are required.

Manually defining sample data for every test is cumbersome. The data is often stale and lacks variety.

A dedicated mock data library like GoFakeIt solves these issues by programmatically generating fresh data on the fly.

Overview of GoFakeIt for Go

GoFakeIt is a popular mock data library ported to Go. It provides data generators for common scenarios like names, addresses, companies, users, transactions, and more.

Some key features:

  • Over 100 data provider methods (and growing).

  • Generates random, unique data every time.

  • Localization support for different locales.

  • Easy to extend with custom data providers.

  • Struct and slice population helpers.

  • Thorough test coverage.

  • MIT license.

The GoFakeIt repo is actively maintained by Brian Voe and has over 500 contributors.

Installing GoFakeIt

To install GoFakeIt, simply run:

go get github.com/brianvoe/gofakeit/v6

Then import it:

import "github.com/brianvoe/gofakeit/v6"

Let's look at how to use it.

Generating Random Fake Data

The basic pattern is to call GoFakeIt data provider methods:

name := gofakeit.Name()
email := gofakeit.Email()
color := gofakeit.Color()

This gives you a fresh, randomized value for each call.

Some handy methods include:

  • Name() - Full fake name

  • Email() - Fake email address

  • Phone() - Random phone number

  • Address() - Fictional street address

  • BS() - Random bullshit (for filler text!)

  • Company() - Fake company name

  • Sentence() - Random sentence

  • paragraphs() - Multiple paragraphs of text

Check the godoc for the full set of data providers available.

Generating Structured Data

For more structured data, GoFakeIt can populate:

  • Structs

  • Slices

  • Maps

  • Arrays

With random values.

NOTE: `fake` struct tags have to be present in the struct for GoFakeIt to produce correct data.

type User  struct {
    ID    int    `fake:"{number:1,100}"`
    Name  string `fake:"{firstname}"`
    Email string `fake:"{email}"`
}

var user User
gofakeit.Struct(&user)

Now user will contain random fake data!

To populate a slice, provide the slice and the desired length:

var users []User
gofakeit.Slice(&users)

This makes mocking datasets a breeze.

Seeding Randomness

By default, each call generates unpredictable data.

To generate repeatable data, seed the RNG:

gofakeit.Seed(1234) // any int64 number

// Repeatable results now
name1 := gofakeit.Name() 
name2 := gofakeit.Name()

Useful for regenerating the same fake datasets.

Examples and Recipes

GoFakeIt is handy for mocking all sorts of data:

  • User accounts

  • Blog posts and comments

  • Product listings

  • Transaction histories

  • File uploads

  • API responses

Some examples:

package main

import (
    "fmt"
    "github.com/brianvoe/gofakeit/v6"
)

type User struct {
    ID    int    `fake:"{number:1,100}"`
    Name  string `fake:"{firstname}"`
    Email string `fake:"{email}"`
}

type Product struct {
    ID          int    `fake:"{number:1,100}"`
    Name        string `fake:"{firstname}"`
    Description string `fake:"{sentence:30}"`
    Price       int    `fake:"{number:1,100}"`
}

func main() {
    // Fake users
    var user User
    gofakeit.Struct(&user)

    fmt.Print(user)
    // Fake product listings

    var product Product
    gofakeit.Struct(&product)

    fmt.Print(product)

    // Fake upload files
    const numFiles = 5
    var files []string
    for i := 0; i < numFiles; i++ {
        files = append(files, gofakeit.ImageURL(50, 50))
    }

    fmt.Print(files)
}

The possibilities are endless!

Conclusion

GoFakeIt for Go makes generating mock data for tests almost too easy. No more hand-rolled stubs that go stale!

Some key benefits:

  • Huge time savings compared to manual mocking.

  • Randomized data that avoids stale samples.

  • Localization for region-specific data.

  • Extensible via custom providers.

  • Helpers for populating structs and slices.

Proper mock data is crucial for writing robust Go tests. GoFakeIt delivers with a robust set of data providers in an easy-to-use package.

I highly recommend installing GoFakeIt in your next Go project. Browse the full docs and examples to see all it can do.

Have you used GoFakeIt in your Go code? Are there any other mock data tools you recommend? Let me know in the comments!

Did you find this article valuable?

Support The Bug Shots by becoming a sponsor. Any amount is appreciated!