Go - Tests

From XennisWiki
Jump to: navigation, search

Write tests for a Go application.

Basics

Write tests with multiple test cases

func Test_myFunc(t *testing.T) {
	tests :=
		[]struct {
			name           string
			input          string
			wantErr        bool
		}{
			{
				name:           "success",
				input:          "some input",
				wantErr:        false,
			},
		}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			err := myFunc(tt.input)
			if (err != nil) != tt.wantErr {
				t.Errorf("got error %v, want error %v", err, tt.wantErr)
			}
		})
	}
}

HTTP server (httptest package)

func myFunc(client *http.Client, url string) error {
	if client == nil {
		client = http.DefaultClient
	}
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	// do something with req
	return nil
}
func Test_fuu(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("some body"))
	}))
	defer server.Close()

	err := myFunc(server.Client(), server.URL)
	if err != nil {
		t.Errorf("got error %v", err)
	}
}

See also