unit-testing - 如何在 golang 中编写关于插入、获取、删除和更新数据的测试用例
问题描述
我必须为插入、获取、删除和更新数据编写测试用例。在互联网上搜索时,我找到了一个代码并且它可以工作,但我不知道它是如何工作的。下面给出了我的代码,任何人都可以简单地告诉我我将如何理解代码。
package models
import(
"testing"
"gopkg.in/mgo.v2/bson"
"fmt"
)
func TestAddBlog(t *testing.T) {
type args struct{
query interface{}
}
tests := []struct{
name string
args args
want bool
}{
{
"first",
args{
bson.M{
"_id" : 4,
"title" : "Life",
"type" : "Motivation",
"description" : "If you skip anything then you will fail in the race of the life....",
"profile_image" : "/image1",
"date_time" : 1536062976,
"author" : "Charliee",
"status" : 1,
"slug" : "abc",
"comment_count" : 100,
"comment_status" : "q",
},
},
true,
},
{
"second",
args{
bson.M{
"_id" : 5,
"title" : "Life",
"type" : "Motivation",
"description" : "If you skip anything then you will fail in the race of the life....",
"profile_image" : "/image1",
"date_time" : 1536062976,
"author" : "Charliee",
"status" : 1,
"slug" : "abc",
"comment_count" : 100,
"comment_status" : "q",
},
},
false,
},
}
for _, k := range tests {
t.Run(k.name, func (t *testing.T) {
err := AddBlog(k.args.query)
fmt.Println(err)
})
}
}
解决方案
下面我提供了一种称为表驱动测试的测试用例形式
type args struct {
}
tests := []struct {
name string
args args
want bool
}{
{
"First",
args{
},
true,
},
{
"Second",
args{
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
})
}
在以下代码中,我们所做的是:
*用三个参数声明一个 Struct([]struct) 切片
1.名称:- 用于命名 t.Run 中的测试。
2.Args:-在这里我们指定我们要测试的函数所需的参数。
3.Want:- 这是布尔表达式,将用于与我们的结果输出进行比较。
现在就像在您的代码中一样,您已经在数据库中添加了一些内容,因此您需要调用一个将获取记录的函数。
如果 err 通过 addblog 函数等于 nil。
之后,您可以比较是否所有值都通过比较并将结果保存为 bool 来保存,我们可以使用它与我们的 want bool 表达式进行比较。
会发生这样的事情:
err:= AddBlog(k.args.query)
if err==nil{
got,err:=fetchBlog(k.args.query)
if val:=err==nil && got.id==id;val!=k.want{
t.Fail()
}
}
注意:这里我比较了 Id 属性,因为它是唯一的。
您需要首先在您的 args 中声明它。
推荐阅读
- amazon-web-services - ansible 打印 ec2_tag 寄存器列表
- c# - 如何在 asp.net core 的基本控制器中处理 On Exception?
- context-free-grammar - L={w| 的 PDA 和 CF 文法 w={a,b}* 使得 2*(w 中“a”-s 的数量)!= 3*(w 中“b”-s 的数量)+2 }
- html - 在 Microsoft Word 上呈现 HTML 标签
- reactjs - 要在表单上添加功能组件的复选框项目
- excel - VBA宏在Sheet1上查找具有数据的单元格范围使用该范围在Sheet2的范围内输入公式
- javascript - 从 .gs 文件到 .js 文件的单个 Google 表格行返回数据
- python - 如何访问一对多关系中的多个字段
- sql - 如何解决公共表表达式的递归成员有多个递归引用?
- linux - 加载的 ELF 段的重叠映射