首页 > 解决方案 > 如何在 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)
        })
    }
} 

标签: unit-testinggo

解决方案


下面我提供了一种称为表驱动测试的测试用例形式

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 中声明它。


推荐阅读