我正在為一個(gè)寧?kù)o的 api 編寫單元測(cè)試,并希望確保得到預(yù)期的響應(yīng)。如何去掉預(yù)期字符串文字末尾的“\n”?我正在使用 stethr 的 testify 包。我曾嘗試使用字符串 TrimSuffix、TrimRight 函數(shù),但沒(méi)有成功。func TestGetConfig(t *testing.T) { testServer := initTestServer(t) req, err := http.NewRequest("GET", "/api/config", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(testServer.getConfig) handler.ServeHTTP(rr, req) //Check the status code is what we expect if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //Check the response body is what we expect. expected := `{"domain":"","ip":"","redirect_key":"mj","redirect_url":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","verification_key":"yp","verification_token":"5a62"}` expected = strings.TrimSuffix(expected, "\n") assert.Equal(t, rr.Body.String(), expected)}我希望測(cè)試能夠通過(guò),但它卻失敗了,并將其作為輸出。Error Trace: config_test.go:94 Error: Not equal: expected: "{\"domain\":\"\",\"ip\":\"\",\"redirect_key\":\"mj\",\"redirect_url\":\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\",\"verification_key\":\"yp\",\"verification_token\":\"5a62\"}\n" actual : "{\"domain\":\"\",\"ip\":\"\",\"redirect_key\":\"mj\",\"redirect_url\":\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\",\"verification_key\":\"yp\",\"verification_token\":\"5a62\"}"
如何修復(fù)原始字符串文字上的失敗斷言
當(dāng)年話下
2023-06-01 09:56:59