How to generate mock test data using Go
Realistic and reliable test data plays a key role in ensuring the quality and functionality of the application. Generating mock data that simulates a real-life scenario is a useful skill for many forms of testing.
There is no support for creating dummy data in the standard library, but many packages exist in Go's broader ecosystem. A popular package for generating dummy data is Gofakeit.
Get started with Gofakeit
Gofakeit is a package that generates dummy data in a Go program. Gofakeit provides rich features, including random data generation that accesses different types. It also offers customization options to adhere to specific formatting standards, localization support and real-time & date generation.
Run this command in your project's working directory, then you have instantiated a new Go project, to add Gofakeit as a third-party dependency:
go get github.com/brianvoe/gofakeit/v6
After adding Gofakeit as a dependency you can import the package as follows:
import ( "github.com/brianvoe/gofakeit/v6" )
Overall, Gofakeit provides most of the functionality of the dummy data generation package.
Generate fake data with Gofakeit
Gofakeit provides functionality to create different data types, including name, email, phone, and business stages…
Here's how you can create dummy data using Gofakeit:
package main import ( "fmt" "github.com/brianvoe/gofakeit/v6" ) func main() { // Tạo tên giả name := gofakeit.Name() fmt.Println("Name:", name) // Tạo địa chỉ email giả email := gofakeit.Email() fmt.Println("Email:", email) // Tạo số điện thoại giả phone := gofakeit.Phone() fmt.Println("Phone:", phone) // Tạo tên công ty giả company := gofakeit.Company() fmt.Println("Company:", company) // Tạo số thẻ tín dụng giả creditCard := gofakeit.CreditCardNumber() fmt.Println("Credit Card:", creditCard) // Tạo giai đoạn hacker giả hackerPhrase := gofakeit.HackerPhrase() fmt.Println("Hacker Phrase:", hackerPhrase) // Tạo tên công việc giả jobTitle := gofakeit.JobTitle() fmt.Println("Job Title:", jobTitle) // Tạo ký hiệu viết tắt tiền tệ giả currency := gofakeit.CurrencyShort() fmt.Println("Currency:", currency) }
The main function generates some dummy values using Gofakeit and prints them to the console using the Println function from the fmt package .
Gofakeit provides struct tags to generate dummy data for different fields. When using the struct tag, Gofakeit initializes the fields with dummy data.
import ( "fmt" "time" "github.com/brianvoe/gofakeit/v6" ) type Person struct { ID string `fake:"{uuid}"` FirstName string `fake:"{firstname}"` LastName string `fake:"{lastname}"` Age int `fake:"{number:18,60}"` Email string `fake:"{email}"` Address string `fake:"{address}"` CreatedAt time.Time `fake:"{date}"` } func main() { var person Person gofakeit.Struct(&person) fmt.Printf("ID: %sn", person.ID) fmt.Printf("First Name: %sn", person.FirstName) fmt.Printf("Last Name: %sn", person.LastName) fmt.Printf("Age: %dn", person.Age) fmt.Printf("Email: %sn", person.Email) fmt.Printf("Address: %sn", person.Address) fmt.Printf("Created At: %sn", person.CreatedAt) }
The fields of struct Person all have a dummy struct tag. In the main function, the variable person is an instance of the struct Person.
The gofakeit.Struct method fills the exported elements of a struct with random data based on the value of the fake tag of the exported fields. The main function then prints the struct fields to the console.
Generate complex dummy data
You can generate complex pseudo-data using Gofakeit, consisting of random sentences, paragraphs, and lorem ipsums with the Sentence , Paragraph , and LoremIpsumParagraph functions respectively .
package main import ( "fmt" "github.com/brianvoe/gofakeit/v6" ) func generateRandomSentence() string { // Tạo câu ngẫu nhiên bằng 6 từ sentence := gofakeit.Sentence(6) return sentence } func generateRandomParagraph() string { // Tạo đoạn ngẫu nhiên bằng 3 câu, mỗi câu có từ 4 tới 8 từ paragraph := gofakeit.Paragraph(3, 4, 8, "/n") return paragraph } func generateLoremIpsum() string { // Tạo 2 đoạn text lorem ipsum, mỗi đoạn có từ 3 tới 5 câu loremIpsum := gofakeit.LoremIpsumParagraph(3, 5, 12, "n") return loremIpsum } func main() { // Thiết lập seed ngẫu nhiên cho kết quả nhất quán (tùy chọn) gofakeit.Seed(0) // Tạo và in câu ngẫu nhiên fmt.Println("Random Sentence:") fmt.Println(generateRandomSentence()) // Tạo và in đoạn ngẫu nhiên fmt.Println("nRandom Paragraph:") fmt.Println(generateRandomParagraph()) // Tạo và in text lorem ipsum fmt.Println("nLorem Ipsum Text:") fmt.Println(generateLoremIpsum()) }
The generateRandomSentence function generates a random sentence with Gofakeit's Sentence function. The generateRandomParagraph function generates a random fragment with the Paragraph function.
The generateLoremIpsum function generates a random lorem ipsum with the LoremIpsumParagraph function.
The main function calls generateRandomSentence , generateRandomParagraph , and generateLoremIpsum . This function prints the results to the console.
Gofakeit simplifies the testing process by generating dynamic data to ensure the ability to meet different requirements. Hope this article helps you better understand this process.
You should read it
- eQuiz - Multiple choice test on programming language C - part 1
- Apple made a comedy music video for up to 5 minutes to mock Windows 95
- Test of programming C P5
- IQ test, IQ test, IQ test, intelligence test
- Multiple choice quiz about Python - Part 4
- Test on C programming P6
- eQuiz - Multiple choice test on OSI Model - part 1
- eQuiz - VB.NET testing test - Part 1
May be interested
- How to check if Windows Defender generates random files and how to fix themover the past few days, many users reported an issue with microsoft defender where it caused the user's disk to fill up. this article, tipsmake will guide you to check and fix this problem.
- Test keyboard online, test key online with the following 5 websiteswhen using the computer you may experience keyboard malfunction, unable to type one or more keys. to determine whether the problem is hardware or software you will have to resort to keyboard test applications.
- What is a stress test?stress testing is the process of determining the ability to maintain a certain level of efficiency in unfavorable conditions of a computer, network, program or device.
- What is fps test? Popular free fps test software todaytop 5 free and popular fps testing software today. this is the savior to help gamers have a smoother, lag-free gaming experience.
- Answers to Test Brain Level 1 to 60 (updated continuously)this is the brain test all levels answers, the easiest brain test solution to support you when you encounter difficulties with brain test's conundrum.
- How to safely stress test overclocked RAM, GPU and CPUstress testing tests the stability of your pc by pushing it to its limits. by the time you finish reading this article, you will be able to stress test your cpu, gpu, and ram.
- Test TCP / IP knowledgea simple and basic test of knowledge around the tcp / ip protocol. you just need to choose which answer is the best and see the final result we give ...
- What do you know about Data Mining? - Part 2how much did you know about data mining? keep testing your knowledge with quantrimang through the following multiple choice questions!
- What is IELTS? Things to know about IELTSielts is currently a certificate of english which is required by many agencies, businesses and international students. so what does ielts mean?
- What do you know about Data Mining? - Part 1how much did you know about data mining? try your knowledge with quantrimang through the following data mining quiz questions!