登录
首页 >  Golang >  Go问答

如何模拟嵌套客户端进行测试

来源:stackoverflow

时间:2024-03-15 20:27:30 433浏览 收藏

在测试基于 GraphQL 的客户端时,模拟嵌套客户端可以帮助创建更全面的测试场景。本文介绍了一种模拟客户端的方法,该方法允许测试各种输入和错误条件。通过使用反射来动态设置响应值,测试用例可以轻松地验证客户端行为并确保其按预期运行。这种模拟技术避免了使用复杂或侵入性的模拟,并使测试用例更易于维护和扩展。

问题内容

我正在构建一个简单的函数,该函数调用一个使用 graphql (https://github.com/machinebox/graphql) 返回 post 的 api。我将逻辑包装在一个服务中,如下所示:

type client struct {
    gcl graphqlclient
}
type graphqlclient interface {
    run(ctx context.context, req *graphql.request, resp interface{}) error
}
func (c *client) getpost(id string) (*post, error) {
    req := graphql.newrequest(`
        query($id: string!) {
          getpost(id: $id) {
            id
            title
          }
        }
    `)
    req.var("id", id)
    var resp getpostresponse
    if err := c.gcl.run(ctx, req, &resp); err != nil {
        return nil, err
    }
    return resp.post, nil
}

现在,我想为 getpost 函数添加测试表,当 id 设置为空字符串时,会出现失败情况,这会导致下游调用 c.gcl.run 出现错误。

我正在努力解决的是 gcl 客户端可以被模拟并被迫返回错误的方式(当没有真正的 api 调用发生时)。

到目前为止我的测试:

package apiClient

import (
    "context"
    "errors"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/google/go-cmp/cmp"
    "github.com/machinebox/graphql"
    "testing"
)

type graphqlClientMock struct {
    graphqlClient
    HasError bool
    Response interface{}
}

func (g graphqlClientMock) Run(_ context.Context, _ *graphql.Request, response interface{}) error {
    if g.HasError {
        return errors.New("")
    }

    response = g.Response

    return nil
}

func newTestClient(hasError bool, response interface{}) *Client {
    return &Client{
        gcl: graphqlClientMock{
            HasError: hasError,
            Response: response,
        },
    }
}

func TestClient_GetPost(t *testing.T) {
    tt := []struct{
        name string
        id string
        post *Post
        hasError bool
        response getPostResponse
    }{
        {
            name: "empty id",
            id: "",
            post: nil,
            hasError: true,
        },
        {
            name: "existing post",
            id: "123",
            post: &Post{id: aws.String("123")},
            response: getPostResponse{
                Post: &Post{id: aws.String("123")},
            },
        },
    }

    for _, tc := range tt {
        t.Run(tc.name, func(t *testing.T) {
            client := newTestClient(tc.hasError, tc.response)
            post, err := client.GetPost(tc.id)

            if err != nil {
                if tc.hasError == false {
                    t.Error("unexpected error")
                }
            } else {
                if tc.hasError == true {
                    t.Error("expected error")
                }
                if cmp.Equal(post, &tc.post) == false {
                    t.Errorf("Response data do not match: %s", cmp.Diff(post, tc.post))
                }
            }
        })
    }
}

我不确定像这样将 response 传递给模拟是否是正确的方法。另外,我很难为响应设置正确的值,因为传递了 interface{} 类型,但我不知道如何将其转换为 getpostresponse 并将值设置为 post


解决方案


您的测试用例不应超出实现范围。我特别指的是空输入与非空输入或任何类型的输入。

让我们看一下您要测试的代码:

func (c *client) getpost(id string) (*post, error) {
    req := graphql.newrequest(`
        query($id: string!) {
            getpost(id: $id) {
                id
                title
            }
        }
    `)
    req.var("id", id)

    var resp getpostresponse
    if err := c.gcl.run(ctx, req, &resp); err != nil {
        return nil, err
    }
    return resp.post, nil
}

上面的实现中没有任何内容基于 id 参数值执行任何操作,因此这段代码的测试中没有任何内容应该真正关心传入的输入内容,如果它与实现无关,它也应该是无关的进行测试。

您的 getpost 基本上有两个代码分支,它们是基于单个因素(即返回的 err 变量的“零”)而采取的。这意味着就您的实现而言,根据 run 返回的 err 值,只有两种可能的结果,因此应该只有两个测试用例,第三个或第四个测试用例只是一个变体,如果不是前两个的完全副本。

您的测试客户端也在做一些不必要的事情,主要的是它的名称,即您所拥有的不是模拟,因此调用它没有帮助。模拟通常不仅仅返回预定义的值,它们还确保按照预期的顺序和预期的参数调用方法等。实际上,您根本不需要这里模拟,所以这是一件好事没有一个。

考虑到这一点,我建议您对测试客户端执行以下操作。

type testgraphqlclient struct {
    resp interface{} // non-pointer value of the desired response, or nil
    err  error       // the error to be returned by run, or nil
}

func (g testgraphqlclient) run(_ context.context, _ *graphql.request, resp interface{}) error {
    if g.err != nil {
        return g.err
    }

    if g.resp != nil {
        // use reflection to set the passed in response value
        // (i haven't tested this so there may be a bug or two)
        reflect.valueof(resp).elem().set(reflect.valueof(g.resp))
    }
    return nil
}

...这是必要的测试用例,全部两个:

func testclient_getpost(t *testing.t) {
    tests := []struct {
        name   string
        post   *post
        err    error
        client testgraphqlclient
    }{{
        name:   "return error from client",
        err:    errors.new("bad input"),
        client: testgraphqlclient{err: errors.new("bad input")},
    }, {
        name:   "return post from client",
        post:   &post{id: aws.string("123")},
        client: testgraphqlclient{resp: getpostresponse{post: &post{id: aws.string("123")}}},
    }}

    for _, tt := range tests {
        t.run(tt.name, func(t *testing.t) {
            client := client{gql: tt.client}
            post, err := client.getpost("whatever")
            if !cmp.equal(err, tt.err) {
                t.errorf("got error=%v want error=%v", err, tt.err)
            }
            if !cmp.equal(post, tt.post) {
                t.errorf("got post=%v want post=%v", post, tt.post)
            }
        })
    }
}

...这里有一些重复,需要两次拼写 posterr ,但与从以下位置填充测试客户端的更复杂/复杂的测试设置相比,这是一个很小的代价。测试用例的预期输出字段。

附录:

如果您要更新 getpost,使其在向 graphql 发送请求之前检查空 id 并返回错误,那么您的初始设置会更有意义:

func (c *client) getpost(id string) (*post, error) {
    if id == "" {
        return nil, errors.new("empty id")
    }
    req := graphql.newrequest(`
        query($id: string!) {
            getpost(id: $id) {
                id
                title
            }
        }
    `)
    req.var("id", id)

    var resp getpostresponse
    if err := c.gcl.run(ctx, req, &resp); err != nil {
        return nil, err
    }
    return resp.post, nil
}

...并相应地更新测试用例:

func TestClient_GetPost(t *testing.T) {
    tests := []struct {
        name   string
        id     string
        post   *Post
        err    error
        client testGraphqlClient
    }{{
        name:   "return empty id error",
        id:     "",
        err:    errors.New("empty id"),
        client: testGraphqlClient{},
    }, {
        name:   "return error from client",
        id:     "nonemptyid",
        err:    errors.New("bad input"),
        client: testGraphqlClient{err: errors.New("bad input")},
    }, {
        name:   "return post from client",
        id:     "nonemptyid",
        post:   &Post{id: aws.String("123")},
        client: testGraphqlClient{resp: getPostResponse{Post: &Post{id: aws.String("123")}}},
    }}

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            client := Client{gql: tt.client}
            post, err := client.GetPost(tt.id)
            if !cmp.Equal(err, tt.err) {
                t.Errorf("got error=%v want error=%v", err, tt.err)
            }
            if !cmp.Equal(post, tt.post) {
                t.Errorf("got post=%v want post=%v", post, tt.post)
            }
        })
    }
}

今天关于《如何模拟嵌套客户端进行测试》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>