在Go语言中生成有效的随机Faker值

huangapple go评论87阅读模式
英文:

Generate Valid Random Faker Values in Go

问题

我正在使用Validator包。我有以下结构体:

type User struct {
    Name       string `validate:"required"`
    Email      string `validate:"required,email"`
    CreditCard string `validate:"credit_card"`
    Password   string `validate:"min=8,max=255"`
}

我该如何生成这些字段的有效随机值?

英文:

I am using Validator package. I have the next Struct:

type User struct {
    Name       string `validate:"required"`
    Email      string `validate:"required,email"`
    CreditCard string `validate:"credit_card"`
    Password   string `validate:"min=8,max=255"`
}

What can I do to generate valid random values for thats fields?

答案1

得分: 3

你可以使用faker包。它具有FirstName()Email()CCNumber()等函数。你还可以在你的结构体中使用标签(onetwo)与该包一起使用。

英文:

You can use faker package. It has functions like FirstName(), Email(), CCNumber(). You can also use tags (one, two) with this package in your struct.

答案2

得分: 1

如果你正在编写测试,你可以使用Fuzzing(在Go 1.18中实现)。

代码看起来像这样:

import "testing"

func TestHello(f *testing.F) {
    // 在这里添加你的种子
    f.add("John", "john@test.com", "1234-5678-1234-5678", "@HelloWorld123")
    
    f.Fuzz(func(t *testing.T, name, email, creditCard, pass string)  {
        // 在这里编写你的测试
    }))
}

然后运行:

$ go test -fuzz
英文:

If you're writing tests, you can use Fuzzing (implemented in Go 1.18).

Would look like this:

import "testing"

func TestHello(f *testing.F) {
    // Add your seeds here
	f.add("John", "john@test.com", "1234-5678-1234-5678", "@HelloWorld123")
    
	f.Fuzz(func(t *testing.T, name, email, creditCard, pass string)  {
		// Write your test here
	}))
}

Then run:

$ go test -fuzz

huangapple
  • 本文由 发表于 2022年8月5日 00:12:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/73239144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定