> For the complete documentation index, see [llms.txt](https://minilabmemo.gitbook.io/golang-memo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://minilabmemo.gitbook.io/golang-memo/monitor-quality/go-test.md).

# go test

### 撰寫

新建一個檔案XX\_test.go，並為 func 取名 TestXXX(t \*testing.T)

```go
func TestXXXt *testing.T) {
	n := XXX(1, 2)
	if n == 3 { // 自己寫if判斷
		t.Log("success")
	} else {
		t.Error("fail") 。
	}

略
if !reflect.DeepEqual(w.Body.String(), expactedResp) {
		t.Errorf("Resp(%s) != expactedResp(%s)", w.Body.String(), expactedResp)
	}
}
```

### 執行

go test -v -cover  ，ｖ代表詳細內容與印出log， cover則可以計算出覆蓋率

更多詳細內容可以看[\[Go 06\] 寫測試並產出一目瞭然的網頁版覆蓋率報告 再也不用怕遺漏](https://minilabmemo.github.io/2020/05/08/05-go-test-coverage/)

#### assert套用

針對判斷的地方可以套用assert 。

```diff
import "github.com/stretchr/testify/assert"

+//使用
assert.Equal(t, http.StatusOK, w.Code)


+//從底層可以看到它幫你把錯誤的輸出log寫好了 超方便  
        	Error:      	Not equal: 
        	            	expected: 200
        	            	actual  : 400
        	Test:       	Test_UpdateInfoBadHandler
```

| 參考                                                                                            | memo                                             |
| --------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| <p><br><a href="https://www.eet-china.com/mp/a41633.html">代码安全性和健壮性：如何在if和assert中做选择?</a></p> | <p>assert/if支持者 <br>為什麼不要自己寫 if 驗證 要用 assert</p> |
| <https://github.com/stretchr/testify>                                                         | assert  範例                                       |
|                                                                                               |                                                  |
