close
close

first Drop

Com TW NOw News 2024

Golang – Generate fake data with GoFakeIt
news

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 concerns about privacy, data availability, and the enormous effort required to collect 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. Using GoFakeIt, developers can quickly populate their testing environments with dummy data, making their testing process more efficient and effective.

Install GoFakeIt

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

go get -u github.com/brianvoe/gofakeit/v6
Go to full screen mode

Exit full screen

Generating Basic Fake Data

Generating basic fake data with GoFakeIt is easy. 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)
}

Go to full screen mode

Exit full screen

output –

Generating Basic Fake Data

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

Adjust fake data

GoFakeIt also offers more granular control over the data generated. You can specify parameters to customize 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)
}


Go to full screen mode

Exit full screen

Output –

Adjust fake data

Use Struct Tags to generate fake data

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

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)
}


Go to full screen mode

Exit full screen

Output –

Use Struct Tags to generate fake data

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

Generate Fake SQL Data

Generating fake SQL data can also be very useful for testing database related code. GoFakeIt can be used to create SQL insert statements filled with fake data. Here’s how:

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)
}

Go to full screen mode

Exit full screen

output –

Generate Fake SQL Data

Randomness in sowing

By default, every call generates unpredictable data.

To generate repeatable data, seed with a number. Seeding makes data repeatable.

gofakeit.Seed(1234) // any int64 number

// Repeatable results now
name1 := gofakeit.Name() 
name2 := gofakeit.Name()
Go to full screen mode

Exit full screen

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 efficiently populate your test environments. By leveraging this library, you can improve your testing process and make it more robust and reliable.