Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

go - Storing a type in a struct for compare

Given the following code: I'm trying to store the type of the mongo client in the struct to later be compared.

func TestGetMongoClient(t *testing.T) {
    type args struct {
        opts *Options
    }
    tests := []struct {
        name    string
        args    args
        want    *mongo.Client
        wantErr bool
    }{
        {name: "Mongo Client Creation", args: args{opts: &opts}, want: , wantErr: nil},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := GetMongoClient(tt.args.opts)
            if (err != nil) != tt.wantErr {
                t.Errorf("GetMongoClient() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            typeCompare = reflect.TypeOf(tt.want) == reflect.TypeOf(got)
            if typeCompare {
                t.Errorf("GetMongoClient() = %v, want %v", got, tt.want)
            }
        })
    }
}

Prior, I had the following code which worked well however I have to translate it into a table based testing structure.

func TestGetMongoConnection(t *testing.T) {
    client, err := GetMongoClient(&opts)
    if err != nil {
        t.Errorf("GetMongoConnect should not return an error but did %d", err)
    }
    result := reflect.TypeOf(&client) == reflect.TypeOf((**mongo.Client)(nil))
    if result == false {
        t.Errorf("Calling GetMongoConnection didn't return a client %d", err)
    }
}

How can I get the table based code to work well?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To compare the type returned from a function to be the same type you want, just declare a new variable with the same type and use reflect.TypeOf to compare:

type Client struct {
    id string
}

func GetClient() *Client {
    return &Client{id: "bla"}
}

func main() {
    want := &Client{}

    fmt.Println(reflect.TypeOf(want) == reflect.TypeOf(GetClient()))
    // prints: true
}

So in your case, want should be declared as &mongo.Client{}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...