我正在为未来的项目编写一个简单的 rest 样板,我目前正在为我的控制器进行一些测试,我正在尝试通过它的 Id 检索待办事项,这/todo/{id}是处理程序。
func (t TodoController) GetById(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id, err := strconv.Atoi(params["id"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
todo, err := t.todoService.GetById(id)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
helpers.SendResponse(http.StatusOK, todo, w)
}
这是此控制器的测试。
var (
todoController TodoController
recorder *httptest.ResponseRecorder
todos []models.Todo
)
func setup() {
todoController = *NewTodoController(services.NewTodoService())
recorder = httptest.NewRecorder()
todos = []models.Todo{
{
ID: 0,
Todo: "Buy milk",
Completed: false,
},
{
ID: 1,
Todo: "Buy cheese",
Completed: false,
},
{
ID: 2,
Todo: "Buy eggs",
Completed: false,
},
}
}
func TestGetById(t *testing.T) {
// Arrange
setup()
request := httptest.NewRequest(http.MethodGet, "/todo/1", nil)
var response models.Todo
// Act
todoController.GetById(recorder, request)
result := recorder.Result()
defer result.Body.Close()
data, err := ioutil.ReadAll(result.Body)
err = json.Unmarshal(data, &response)
// Assert
if err != nil {
t.Errorf("Expected error to be nil but got %v", err)
}
assert.Equal(t, result.StatusCode, http.StatusOK, "Response should have been 200 Ok")
assert.Equal(t, response, todos[1], "Response did not match the expected result")
}
看起来当向/todo/1mux 发送请求时无法检索 Id,因此它最终返回 BadRequest 错误。
这是此回购协议的链接:https ://github.com/Je12emy/rest_boiler
aluckdog
相关分类