I'm trying to unit test a constructor for a struct with many fields. I want to make sure that the constructor performs all the expected validations so I am testing single fields for multiple failure scenarios.
I'm trying to do this programatically so I'm using table tests, however this leads to a lot of repetition and noise in the tests as I end up repeating N param fields just to test for the one field error.
For example:
func NewSomeObject(p *Params) *SomeObject {
...
}
type SomeObject struct {
..
Field1 string
Field2 string
Field3 string
...
Field10 string
}
func TestNewSomeObject(t *testing.T) {
tcases := map[string]struct {
params *Params
err error
}{
&Params{
Field1: "invalid_0" // <--- making sure that this invalid field is caught
Field2: "valid"
Field3: "valid"
...
Field10: "valid"
},
&Params{
Field1: "invalid_1" // <--- another invalid case
Field2: "valid"
Field3: "valid"
...
Field10: "valid"
},
&Params{
Field1: "invalid_2"
Field2: "valid"
Field3: "valid"
...
Field10: "valid"
},
&Params{
Field1: "invalid_3"
Field2: "valid"
Field3: "valid"
...
Field10: "valid"
},
...
...
...
}
for name, tc := range tcases {
t.Logf("Running test %s", name)
s, err := NewSomeObject(tc.params)
if !reflect.DeepEqual(tc.err, err) {
t.Fatalf("Got '%v', Expected: '%v'", err, tc.err)
}
}
}
Is there a better way to vary a single field in the struct without having to repeat the input so many times?