How to use different mocks for different subtests when using table driven tests in Golang?

29 views Asked by At

I have the following table-driven test in go:

    func Test_funcTest(t *testing.T) {
        
        mockStr := "str"
    
        type args struct {
            arg1 String
            arg2 String
        }
        
        tests := []struct {
            name    string
            args    args
            want    string
            wantErr bool
        }{
            {
                name: "test1",
                args: args{
                    arg1: "arg1",
                    arg2: "arg2",
                },
                want:    "res1",
                wantErr: false,
            },
            {
                name: "test2",
                args: args{
                    arg1: "arg1",
                    arg2: "arg2",
                },
                want: "res2",
                wantErr: false,
            },
        }
        for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {

            got, err := funcTest(tt.args.arg1, tt.args.arg2)
            if (err != nil) != tt.wantErr {
                t.Errorf("funcTest() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("funcTest() = %v, want %v", got, tt.want)
            }
        })
    }
}

I am mocking the mockStr string that the funcTest() method uses during it's execution. test1 modifies the mockStr string and this modified version is used by test2. How can I mock two different versions of the mockStr string for these 2 tests?

Thanks!

0

There are 0 answers