jeudi 10 décembre 2020

Mocking a struct's method call in go tests

I am looking to mock a method of a struct in tests to improve code coverage. There are a few posts regarding this, none of them are working for me. I might have gotten this completely wrong.

main/file1.go

type application struct {
    Name string
 }

func (app *application) find() error {
    // perform function logic
    return nil
}

func main() {
    app := &application{
        Name:   "Main Application",
    }

    err := app.find()
    if err != nil {
        fmt.Printf("Error in find call: %s\n", err)
    }
}

I need to be able to mock test for find() and return an error (I would not want to generate a test case that could result in an error as this is not under my control and I am not sure how to generate one by passing acceptable params). I tried to follow the second answer from this post and the compiler is not liking it.

main/file1_test.go

func Test_application_find(t *testing.T) {
    tests := []struct {
        name           string
        app            *application
        wantErr        string
    }{
        {
            name: "generate error",
            app: &application{
                Name: "Mock Application",
            },
            wantErr: true,
        },
    }
    for _, tt := range tests {
        mockCaller := tt.app.find // this works fine
        tt.app.find = func() error { // this assignment errors out
            return fmt.Errorf("Mock Error Message")
        }
        defer func() {
            tt.app.find = mockCaller // this assignment errors out
        }()

        t.Run(tt.name, func(t *testing.T) {
            if err := tt.app.find(); (err != nil) && (err.Error() != "Mock Error Message") {
                    t.Errorf("error = %s, wantErr %s", err.Error(), tt.wantErr)
            }
        } 
    }
}

What am I doing wrong here? Please suggest.

Aucun commentaire:

Enregistrer un commentaire