## 測試
### 測試處理程序 (Testing handler)
`GET` `/users/:id`
下面的處理程序是根據用戶的 id 從數據庫取到該用戶數據,如果用戶不存在則返回 `404` 和提示語句。
#### 創建 User
`POST` `/users`
- 接受 JSON 格式的關鍵信息
- 創建成功返回 `201 - Created`
- 發生錯誤返回 `500 - Internal Server Error`
#### 獲取 User
`GET` `/users/:email`
- 獲取成功返回 `200 - OK`
- 未獲取 User 返回 `404 - Not Found`
- 發生其它錯誤返回 `500 - Internal Server Error`
`handler.go`
```go
package handler
import (
"net/http"
"github.com/labstack/echo"
)
type (
User struct {
Name string `json:"name" form:"name"`
Email string `json:"email" form:"email"`
}
handler struct {
db map[string]*User
}
)
func (h *handler) createUser(c echo.Context) error {
u := new(User)
if err := c.Bind(u); err != nil {
return err
}
return c.JSON(http.StatusCreated, u)
}
func (h *handler) getUser(c echo.Context) error {
email := c.Param("email")
user := h.db[email]
if user == nil {
return echo.NewHTTPError(http.StatusNotFound, "user not found")
}
return c.JSON(http.StatusOK, user)
}
```
`handler_test.go`
```go
package handler
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
var (
mockDB = map[string]*User{
"jon@labstack.com": &User{"Jon Snow", "jon@labstack.com"},
}
userJSON = `{"name":"Jon Snow","email":"jon@labstack.com"}`
)
func TestCreateUser(t *testing.T) {
// 設置
e := echo.New()
req := httptest.NewRequest(echo.POST, "/", strings.NewReader(userJSON))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
h := &handler{mockDB}
// 斷言
if assert.NoError(t, h.createUser(c)) {
assert.Equal(t, http.StatusCreated, rec.Code)
assert.Equal(t, userJSON, rec.Body.String())
}
}
func TestGetUser(t *testing.T) {
// 設置
e := echo.New()
req := httptest.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
c.SetPath("/users/:email")
c.SetParamNames("email")
c.SetParamValues("jon@labstack.com")
h := &handler{mockDB}
// 斷言
if assert.NoError(t, h.getUser(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, userJSON, rec.Body.String())
}
}
```
#### 使用 Form 表單作為關鍵信息
```go
f := make(url.Values)
f.Set("name", "Jon Snow")
f.Set("email", "jon@labstack.com")
req := httptest.NewRequest(echo.POST, "/", strings.NewReader(f.Encode()))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm)
```
#### 設置路徑 (Path) 參數
```go
c.SetParamNames("id", "email")
c.SetParamValues("1", "jon@labstack.com")
```
#### 設置查詢 (Query) 參數
```go
q := make(url.Values)
q.Set("email", "jon@labstack.com")
req := http.NewRequest(echo.POST, "/?"+q.Encode(), nil)
```
### 測試中間件
*待定*
你可以在[這里](https://github.com/labstack/echo/tree/master/middleware)查看框架自帶中間件的測試代碼。