Open tokubass opened 5 years ago
I'm afraid this feature is a bit impossible, as I stated here: https://github.com/bxcodec/faker#limitation
I will grateful if someone can give solutions for this issue.
So due to a recent PR that was merged, what you are asking is now possible as long as you add a custom tag to your struct and use AddProvider()
to implement what happens when you use that tag.
@bxcodec & @tokubass
Example:
type MyInt int
type Sample struct {
Value []MyInt `faker:"myint"` // <- the custom tag
}
func TestArrayOfCustomType(t *testing.T) {
a := Sample{}
sliceLen := 10
err := AddProvider("myint", func(v reflect.Value) (interface{}, error) {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
r := make([]MyInt, sliceLen)
for i := range r {
r[i] = MyInt(r1.Intn(100))
}
return r, nil
})
/** ^ above is the AddProvider for the tag "myint".
* It simply makes a slice of length 10 and fills it with random numbers.
* That is the implementation for what happens when you use the tag.
*/
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
err = FakeData(&a)
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
if len(a.Value) != sliceLen {
t.Errorf("Expected a slice of length %v but got %v", sliceLen, len(a.Value))
}
}
~This fix currently only works for types of array & slice. I can submit a PR that will extend this behavior to more types shortly (aliasing an existing built-in type to a user defined type).~
Edited: ^ I was ignorant of some existing code. I have added a unit test for the OP's situation, but as explained in the previous comment, just use AddProvider()
to ensure it's created properly
@bxcodec I think you can close this issue as the OP's desire is now supported with the caveat of using AddProvider()
to make sure the custom type gets created properly.
I want to get this sample code supported.