Go: test 測試測到老 要飯要到飽~
真心覺得長大了 :) 加油!!!!
go test
-
命名規則:
-
檔案名稱_test
就這樣 func TESTxxx(*testing.T)
-
-
指令
go test
-
go test -v
- 會顯示花多久
-
example
package main import "testing" func Add(x, y int) int { return x + y } type AddResult struct { x int y int expected int } var addResult = []AddResult{ {1, 1, 2}, } func TestAdd( t *testing.T) { for _, test := range addResult { result := Add(test.x, test.y) if (result != test.expected) { t.Fatal("Expected Result Not Given!") } } }
-
cmd result
E:\阿葛\windows-mac-sharing-workspace\go\yuting-exercies\test>go test PASS ok _/E_/阿葛/windows-mac-sharing-workspace/go/yuting-exercies/test 0.164s E:\阿葛\windows-mac-sharing-workspace\go\yuting-exercies\test>go test -v === RUN TestAdd --- PASS: TestAdd (0.00s) PASS ok _/E_/阿葛/windows-mac-sharing-workspace/go/yuting-exercies/test 0.159s
-
棒棒影片
Go Api test:
- example
"net/http"
"net/http/httptest"
"github.com/stretchr/testify/assert"
"testing"
func TestCustomer(t *testing.T){
w := httptest.NewRecorder()
// method url body
req, _ = http.NewRequest("GET", "/customer", nil)
router.ServeHttp(w, req)
// expected messages
assert.Equal(t, 200, w.Code, "return status code should be 200")
}
概念就是:
- httptest.NewRecorder: 幫我記錄我寫的 API(GIN) 回傳內容
- http.NewRequest: 送出
request
去吃我寫的API- router 就是我用 gin 寫的 api
- 用 gin 的 ServeHttp Run 起來
- asseet: 再來用直接看回傳的內容是不是預期的樣子
整個感覺就很美~
postman
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
let jsonData = pm.response.json();
console.log(jsonData)
pm.test("[GET]", function () {
pm.expect(jsonData[0].uuid).to.eq("c439f7a8-ec2e-41cc-9e61-6f973a7f952a");
pm.expect(jsonData[0].len).to.eq(1);
pm.expect(jsonData[0].name).to.eq("tim");
});
Reference:
-
https://www.katalon.com/resources-center/blog/api-testing-tips/
- Positive test
- Verify that the API receives input and returns the expected output as specified in the requirement.
- Verify that the response status code is returned as specified in the requirement, whether it returns a 2xx or error code.
- Specify input with minimum required fields and with maximum fields.
- Negative test
- Verify that the API returns an appropriate response when the expected output does not exist.
- Perform input validation test.
- Verify the API’s behaviors with different levels of authorization.