I have to write the test cases for the inserting, fetching, deletion and updating the data. While searching on the internet I found a code and it works but I don't know how it works exactly. The code I have is given below can anybody please tell me in easy way that how I will understand the code.
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)
})
}
}
Below I Have Provided With The Form Of Test Case Known as Table Driven Tests
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) {
})
}
In The Following Code What we Do is:
*Declare A Slice of Struct([]struct) With Three Parameters
1.Name:- It Would Be used For naming the Test in t.Run.
2.Args:- Here We Specify the arguments That Are needed By The Function We are Going To Test.
3.Want:- This is the bool expression which will be used For Comparison with The output of our Result.
Now as in Your Code You have Added Something in the Database so You Need To call a Function Which Will Fetch the record.
If the err is equal to nil by the addblog Function.
After That You can Compare if all of the values are saved by comparing and saving the result as a bool which we can use for comparison with our want bool expression.
Something Like this Will happen:
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()
}
}
Note: Here I have Compared The Id Attribute as it Will be Unique .
You Need To Declare that in Your args First.