基础单元测试

  1. package listing01
  2. import (
  3. "net/http"
  4. "testing"
  5. )
  6. const checkMark = "\u2713"
  7. const ballotX = "\u2717"
  8. func TestDownload(t *testing.T) {
  9. url := "http://www.baidu.com"
  10. statusCode := 200
  11. t.Log("Given the need to test downloading content.")
  12. {
  13. t.Logf("\tWhen checking \"%s\" for status code \"%d\"", url, statusCode)
  14. {
  15. resp, err := http.Get(url)
  16. if err != nil {
  17. t.Fatal("\t\tShould be able to make the Get call.", ballotX, err)
  18. }
  19. t.Log("\t\tShould be able to make th Get call.", checkMark)
  20. defer resp.Body.Close()
  21. if resp.StatusCode == statusCode {
  22. t.Logf("\t\tShould receive a \"%d\" status. %v", statusCode, checkMark)
  23. } else {
  24. t.Errorf("\t\tShould receive a \"%d\" status. %v %v", statusCode, ballotX, resp.StatusCode)
  25. }
  26. }
  27. }
  28. }

表组测试

  1. package listing08
  2. import (
  3. "net/http"
  4. "testing"
  5. )
  6. const checkMark = "\u2713"
  7. const ballotX = "\u2717"
  8. func TestDownload(t *testing.T) {
  9. var urls = []struct {
  10. url string
  11. statusCode int
  12. }{
  13. {
  14. "http://www.baidu.com",
  15. http.StatusOK,
  16. },
  17. {
  18. "http://www.baidu.com/dasda",
  19. http.StatusNotFound,
  20. },
  21. }
  22. t.Logf("Given the need to test downloading different content.")
  23. {
  24. for _, u := range urls {
  25. t.Logf("\tWhen checking \"%s\" for status code \"%d\"", u.url, u.statusCode)
  26. {
  27. resp, err := http.Get(u.url)
  28. if err != nil {
  29. t.Fatal("\t\tShould be able to Get the url.", ballotX, err)
  30. }
  31. t.Log("\t\tShould be able to Get the url", checkMark)
  32. defer resp.Body.Close()
  33. if resp.StatusCode == u.statusCode {
  34. t.Logf("\t\tShould have a \"%d\" status. %v", u.statusCode, checkMark)
  35. } else {
  36. t.Errorf("\t\tShould have a \"%d\" status %v %v", u.statusCode, ballotX, resp.StatusCode)
  37. }
  38. }
  39. }
  40. }
  41. }