基础单元测试
package listing01import ( "net/http" "testing")const checkMark = "\u2713"const ballotX = "\u2717"func TestDownload(t *testing.T) { url := "http://www.baidu.com" statusCode := 200 t.Log("Given the need to test downloading content.") { t.Logf("\tWhen checking \"%s\" for status code \"%d\"", url, statusCode) { resp, err := http.Get(url) if err != nil { t.Fatal("\t\tShould be able to make the Get call.", ballotX, err) } t.Log("\t\tShould be able to make th Get call.", checkMark) defer resp.Body.Close() if resp.StatusCode == statusCode { t.Logf("\t\tShould receive a \"%d\" status. %v", statusCode, checkMark) } else { t.Errorf("\t\tShould receive a \"%d\" status. %v %v", statusCode, ballotX, resp.StatusCode) } } }}
表组测试
package listing08import ( "net/http" "testing")const checkMark = "\u2713"const ballotX = "\u2717"func TestDownload(t *testing.T) { var urls = []struct { url string statusCode int }{ { "http://www.baidu.com", http.StatusOK, }, { "http://www.baidu.com/dasda", http.StatusNotFound, }, } t.Logf("Given the need to test downloading different content.") { for _, u := range urls { t.Logf("\tWhen checking \"%s\" for status code \"%d\"", u.url, u.statusCode) { resp, err := http.Get(u.url) if err != nil { t.Fatal("\t\tShould be able to Get the url.", ballotX, err) } t.Log("\t\tShould be able to Get the url", checkMark) defer resp.Body.Close() if resp.StatusCode == u.statusCode { t.Logf("\t\tShould have a \"%d\" status. %v", u.statusCode, checkMark) } else { t.Errorf("\t\tShould have a \"%d\" status %v %v", u.statusCode, ballotX, resp.StatusCode) } } } }}