如何模拟嵌套客户端进行测试
来源: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)
}
})
}
}
...这里有一些重复,需要两次拼写 post 和 err ,但与从以下位置填充测试客户端的更复杂/复杂的测试设置相比,这是一个很小的代价。测试用例的预期输出字段。
附录:
如果您要更新 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学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习