package main import "testing" func Add(x, y int) int { return x + y } func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("Expected 5, but got %d", result) } }
package main import "testing" func Add(x, y int) int { return x + y } func TestAdd(t *testing.T) { tests := []struct { x, y, want int }{ {2, 3, 5}, {5, 7, 12}, {10, 0, 10}, {-5, -7, -12}, } for _, test := range tests { result := Add(test.x, test.y) if result != test.want { t.Errorf("Add(%d, %d) = %d; want %d", test.x, test.y, result, test.want) } } }
package main import ( "net/http" "net/http/httptest" "testing" ) func MakeRequest() string { resp, _ := http.Get("http://example.com") defer resp.Body.Close() return resp.Status } func TestMakeRequest(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) })) defer ts.Close() resp := httptest.NewRecorder() MakeRequest() if resp.Code != http.StatusOK { t.Errorf("Expected HTTP status %d but got %d", http.StatusOK, resp.Code) } }Here, we have defined the `MakeRequest` function which makes an HTTP GET request using the `net/http` package, and returns the status of the response. In the `TestMakeRequest` function, we first create a test server using `httptest.NewServer`, and define a handler function which returns an HTTP 200 response with a body of "OK". We then make a call to `MakeRequest`, which should use the mock server instead of the real HTTP server to make the request. Finally, we check if the expected HTTP status code was returned using `t.Errorf`. Package library: `testing`, `net/http`, `net/http/httptest`