Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varying a struct field for unit testing

Tags:

go

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?

like image 981
user7467314 Avatar asked Mar 09 '26 21:03

user7467314


1 Answers

You can avoid repetitive code by creating one constructor that would set up all default values (valid).

The constructor can also receive a function to operate over the created object before returning it.

That way, you only need to code the logic required to invalidate the particular field you'd like to test.

To create a Params object you can just do:

params1 := CreateParamsWith(func(p *Params) {
    p.Field1 = "invalid_0"
})

The CreateParamsWith might look like this:

func CreateParamsWith(modifyParams func(*Params)) (*Params) {
    params := &Params{  
        Field1: "valid",
        Field2: "valid",
        Field3: "valid",
        Field4: "valid",
        Field5: "valid",
        }
    modifyParams(params)
    return params
}

Full working code here: https://play.golang.org/p/U0xhtIbQfy

like image 65
eugenioy Avatar answered Mar 12 '26 12:03

eugenioy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!