DEV Community

Cover image for Golang - Generate Fake Data With GoFakeIt
Ankit malik
Ankit malik

Posted on

Golang - Generate Fake Data With GoFakeIt

Introduction

In software development, testing is crucial to ensure that code works as expected. However, obtaining real data for testing purposes can be challenging due to privacy concerns, data availability, and the sheer effort required to gather and sanitize it. This is where generating fake data becomes invaluable. In the Go programming language, one of the most popular libraries for generating fake data is GoFakeIt.

What is GoFakeIt?

GoFakeIt is a robust library that allows developers to generate a wide range of random data for testing purposes. It supports the creation of realistic fake data for names, addresses, email addresses, phone numbers, dates, and many other types of information. By using GoFakeIt, developers can quickly populate their test environments with dummy data, making their testing process more efficient and effective.

Installing GoFakeIt

To get started with GoFakeIt, you first need to install the library. You can do this using the go get command:

go get -u github.com/brianvoe/gofakeit/v6
Enter fullscreen mode Exit fullscreen mode

Generating Basic Fake Data

Generating basic fake data with GoFakeIt is straightforward. Here are some examples:

package main

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

func main() {
    // Seed the random generator
    gofakeit.Seed(0)

    // Generate a fake name
    name := gofakeit.Name()
    fmt.Println("Name:", name)

    // Generate a fake email address
    email := gofakeit.Email()
    fmt.Println("Email:", email)

    // Generate a fake phone number
    phone := gofakeit.Phone()
    fmt.Println("Phone:", phone)

    // Generate a fake address
    address := gofakeit.Address()
    fmt.Println("Address:", address.Address)
}

Enter fullscreen mode Exit fullscreen mode

output -

Generating Basic Fake Data

This script seeds the random generator to ensure reproducibility and then generates a fake name, email, phone number, and address. The output will be different each time you run the program unless you use the same seed value.

Customizing Fake Data

GoFakeIt also allows for more granular control over the generated data. You can specify parameters to tailor the data to your needs. For example:

package main

import (
    "fmt"

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

func main() {
    // Seed the random generator
    gofakeit.Seed(0)

    // Generate a fake person with specific attributes
    person := gofakeit.Person()
    fmt.Println("First Name:", person.FirstName)
    fmt.Println("Last Name:", person.LastName)
    fmt.Println("Email:", person.Contact.Email)
    fmt.Println("Phone:", person.Contact.Phone)
    fmt.Println("SSN:", person.SSN)

    // Generate a fake credit card
    creditCard := gofakeit.CreditCard()
    fmt.Println("Credit Card Number:", creditCard.Number)
    fmt.Println("Credit Card Expiration:", creditCard.Exp)
    fmt.Println("Credit Card CVV:", creditCard.Cvv)
}


Enter fullscreen mode Exit fullscreen mode

Output -

Customizing Fake Data

Using Struct Tags to Generate Fake Data

One of the powerful features of GoFakeIt is its ability to generate fake data directly into struct fields using struct tags. Here’s how you can do it:

package main

import (
    "fmt"

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

type User struct {
    FirstName string `fake:"{firstname}"`
    LastName  string `fake:"{lastname}"`
    Email     string `fake:"{email}"`
    Phone     string `fake:"{phone}"`
    Birthdate string `fake:"{date}"`
}

func main() {
    // Seed the random generator
    gofakeit.Seed(0)

    var user User
    gofakeit.Struct(&user)

    fmt.Printf("User: %+v\n", user)

    users := []User{}
    gofakeit.Slice(&users)
    fmt.Printf("lenght: %d ,Users: %+v\n", len(users), users)
}


Enter fullscreen mode Exit fullscreen mode

Output -

Using Struct Tags to Generate Fake Data

In this example, the User struct is populated with fake data using the struct tags. This feature is particularly useful for generating large amounts of structured data quickly.

Generating Fake SQL data

Generating fake SQL data can also be extremely helpful for testing database-related code. GoFakeIt can be used to create SQL insert statements populated with fake data. Here’s how you can do it:

package main

import (
    "fmt"

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

func main() {
    // Seed the random generator
    gofakeit.Seed(0)

    sqloptions := &gofakeit.SQLOptions{
        Table: "people", // table name
        Count: 2, // count of sql records
        Fields: []gofakeit.Field{
            {Name: "id", Function: "autoincrement"},
            {Name: "first_name", Function: "firstname"},
            {Name: "price", Function: "price"},
            {Name: "age", Function: "number", Params: gofakeit.MapParams{"min": {"1"}, "max": {"99"}}},
            {Name: "created_at", Function: "date", Params: gofakeit.MapParams{"format": {"2006-01-02 15:04:05"}}},
        },
    }

    sqlData, err := gofakeit.SQL(sqloptions)
    fmt.Println("err - ", err)
    fmt.Println(sqlData)
}

Enter fullscreen mode Exit fullscreen mode

output -

Generating Fake SQL data

Seeding Randomness

By default, each call generates unpredictable data.

To generate repeatable data, seed with a number. With Seeding data will be repetable.

gofakeit.Seed(1234) // any int64 number

// Repeatable results now
name1 := gofakeit.Name() 
name2 := gofakeit.Name()
Enter fullscreen mode Exit fullscreen mode

Conclusion

Generating fake data is an essential part of testing in software development. GoFakeIt provides a powerful and flexible way to create realistic fake data in Go. Whether you need simple random strings or complex data structures, GoFakeIt can help you populate your test environments efficiently. By leveraging this library, you can enhance your testing process, making it more robust and reliable.

Top comments (0)