我必须编写用于插入,获取,删除和更新数据的测试用例。在互联网上搜索时,我发现了一个代码并且它有效,但我不知道它是如何工作的。我的代码如下所示,任何人都可以通过简单的方式告诉我如何理解代码。
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.Name:-它将用于在t.Run中命名测试。
2.Args: - 这里我们指定我们要测试的函数所需的参数。
3.Want: - 这是bool表达式,用于与Result的输出进行比较。
现在和你的代码一样,你已经在数据库中添加了一些东西,所以你需要调用一个可以获取记录的函数。
如果错误由addblog函数等于nil。
之后您可以通过比较并保存结果作为bool来比较是否保存了所有值,我们可以将其用于与我们想要的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中声明它。