In the last article, we introduced the table-driven testing method and gomock testing framework, which greatly improved the efficiency and quality of testing. This section describes how to use assertions in your testing to improve efficiency and quality.

Why do YOU need an assertion library

Let’s take a look at why there are no assertions in the Go standard pack, which is answered in the OFFICIAL FAQ.

Golang.org/doc/faq#ass…

The general idea is: “Go does not provide assertions, which we know can be inconvenient, but the main purpose is to prevent you programmers from being lazy on error handling. We know it’s an argument, but we think it’s cool.” So it’s easy to see why we introduced the assertion library: lazy, it’s convenient to introduce assertions to make testing more efficient and code more readable.

testify

We don’t seem to have a lot of choice in the assertion library, all of us are pretty good at start and activity.

Github.com/stretchr/te…

All of us can do no harm without comparison. Can we look at the potency test before using potency?

func TestSomeFun(t *testing.T){
...
    ifv ! = want { t.Fatalf("V value error, expected value: %s, actual value: %s", want, v)
    }
    iferr ! = nil { t.Fatalf("Unexpected error: %s", err)
    }
    ifobjectA ! = objectB {ifobjectA.field1 ! = objectb.field1 {// t.patalf () field1 error... bla bla bla }ifobjectA.field2 ! = objectb.field2 {// t.patalf () field2 error... Bla bla bla} bla bla bla } ... }Copy the code

The code above is riddled with a lot of if… else.. Judgment, piecing together large chunks of misinformation (really manual work…) It is not intuitive and inefficient, and it is really not fashion. Now, we can modify the sample test above using Potency:

func TestSomeFun(t *testing.T){
    a := assert.New(t)
...
    a.Equal(v, want)
    a.Nil(err,"If you still want to print your own error message, you can pass the third parameter.")
    a.Equal(objectA, objectB)
...
}
Copy the code

Three lines done, the meaning of the test at a glance — intuitive, efficient, short, fashion.

To summarize

All of us can testify to the potency of a lazy person who can fall in love with only once. Using a combination of table-driven tests, Gomock and Potency, we were able to write nice unit test code. However, it’s not enough to test the elegance of the code, we also need to spruce up Main.go. In the next and final article in this series, we’ll introduce the Wire dependency injection framework to help main.go slim down.