Skip to content

Commit

Permalink
#18 Implement unit test for book controller
Browse files Browse the repository at this point in the history
  • Loading branch information
ybkuroki committed Jun 28, 2020
1 parent 0e75c25 commit 40f7011
Show file tree
Hide file tree
Showing 8 changed files with 242 additions and 56 deletions.
2 changes: 1 addition & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func Load() {
flag.Parse()
config = &Config{}
if err := configor.Load(config, "application."+*env+".yml"); err != nil {
fmt.Println(err.Error)
fmt.Println(err)
}
}

Expand Down
8 changes: 4 additions & 4 deletions controller/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (

func TestGetLoginStatus(t *testing.T) {
router := test.Prepare()
router.GET("/api/account/loginStatus", GetLoginStatus())
router.GET(APIAccountLoginStatus, GetLoginStatus())

req := httptest.NewRequest("GET", "/api/account/loginStatus", nil)
req := httptest.NewRequest("GET", APIAccountLoginStatus, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)
Expand All @@ -24,9 +24,9 @@ func TestGetLoginStatus(t *testing.T) {

func TestGetLoginAccount(t *testing.T) {
router := test.Prepare()
router.GET("/api/account/loginAccount", GetLoginAccount())
router.GET(APIAccountLoginAccount, GetLoginAccount())

req := httptest.NewRequest("GET", "/api/account/loginAccount", nil)
req := httptest.NewRequest("GET", APIAccountLoginAccount, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)
Expand Down
41 changes: 41 additions & 0 deletions controller/api_const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package controller

const (
// API represents the group of API.
API = "/api"
// APIBook represents the group of book management API.
APIBook = API + "/book"
// APIBookList is
APIBookList = APIBook + "/list"
// APIBookSearch is
APIBookSearch = APIBook + "/search"
// APIBookRegist is
APIBookRegist = APIBook + "/new"
// APIBookEdit is
APIBookEdit = APIBook + "/edit"
// APIBookDelete is
APIBookDelete = APIBook + "/delete"
)

const (
// APIMaster represents the group of master management API.
APIMaster = API + "/master"
// APIMasterCategory is
APIMasterCategory = APIMaster + "/category"
// APIMasterFormat is
APIMasterFormat = APIMaster + "/format"
)

const (
// APIAccount represents the group of account management API.
APIAccount = API + "/account"
// APIAccountLoginStatus is
APIAccountLoginStatus = APIAccount + "/loginStatus"
// APIAccountLoginAccount is
APIAccountLoginAccount = APIAccount + "/loginAccount"
)

const (
// APIHealth is
APIHealth = API + "/health"
)
129 changes: 116 additions & 13 deletions controller/book_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,140 @@ import (
"github.com/stretchr/testify/assert"
"github.com/ybkuroki/go-webapp-sample/model"
"github.com/ybkuroki/go-webapp-sample/model/dto"
"github.com/ybkuroki/go-webapp-sample/repository"
"github.com/ybkuroki/go-webapp-sample/test"
)

func TestGetBookList(t *testing.T) {
router := test.Prepare()
router.GET(APIBookList, GetBookList())

setUpTestData()

uri := test.NewRequestBuilder().URL(APIBookList).Params("page", "0").Params("size", "5").Build().GetRequestURL()
req := httptest.NewRequest("GET", uri, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindAllByPage(repository.GetRepository(), 0, 5)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestGetBookSearch(t *testing.T) {
router := test.Prepare()
router.GET(APIBookSearch, GetBookSearch())

setUpTestData()

uri := test.NewRequestBuilder().URL(APIBookSearch).Params("query", "Test").Params("page", "0").Params("size", "5").Build().GetRequestURL()
req := httptest.NewRequest("GET", uri, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByTitle(repository.GetRepository(), "Test", 0, 5)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookRegist(t *testing.T) {
router := test.Prepare()
router.POST("/api/book/new", PostBookRegist())
router.POST(APIBookRegist, PostBookRegist())

param := &dto.RegBookDto{
Title: "Test1",
Isbn: "123-123-123-1",
CategoryID: 1,
FormatID: 1,
}
param := createRegDto()
req := httptest.NewRequest("POST", APIBookRegist, strings.NewReader(test.ConvertToString(param)))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
rec := httptest.NewRecorder()

req := httptest.NewRequest("POST", "/api/book/new", strings.NewReader(test.ConvertToString(param)))
router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookEdit(t *testing.T) {
router := test.Prepare()
router.POST(APIBookEdit, PostBookEdit())

setUpTestData()

param := createChgDto()
req := httptest.NewRequest("POST", APIBookEdit, strings.NewReader(test.ConvertToString(param)))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func TestPostBookDelete(t *testing.T) {
router := test.Prepare()
router.POST(APIBookDelete, PostBookDelete())

setUpTestData()

book := &model.Book{}
data, _ := book.FindByID(repository.GetRepository(), 1)

param := createChgDto()
req := httptest.NewRequest("POST", APIBookDelete, strings.NewReader(test.ConvertToString(param)))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

data := &model.Book{
assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
}

func setUpTestData() {
model := &model.Book{
ID: 1,
Title: "Test1",
Isbn: "123-123-123-1",
CategoryID: 1,
Category: &model.Category{1, "技術書"},
Category: &model.Category{ID: 1, Name: "技術書"},
FormatID: 1,
Format: &model.Format{1, "書籍"},
Format: &model.Format{ID: 1, Name: "書籍"},
}
repo := repository.GetRepository()
model.Save(repo)
}

assert.Equal(t, http.StatusOK, rec.Code)
assert.JSONEq(t, test.ConvertToString(data), rec.Body.String())
func createRegDto() *dto.RegBookDto {
dto := &dto.RegBookDto{
Title: "Test1",
Isbn: "123-123-123-1",
CategoryID: 1,
FormatID: 1,
}
return dto
}

func createChgDto() *dto.ChgBookDto {
dto := &dto.ChgBookDto{
ID: 1,
Title: "EditedTest1",
Isbn: "234-234-234-2",
CategoryID: 2,
FormatID: 2,
}
return dto
}
4 changes: 2 additions & 2 deletions controller/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import (

func TestGetHealthCheck(t *testing.T) {
router := test.Prepare()
router.GET("/api/health", GetHealthCheck())
router.GET(APIHealth, GetHealthCheck())

req := httptest.NewRequest("GET", "/api/health", nil)
req := httptest.NewRequest("GET", APIHealth, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)
Expand Down
18 changes: 9 additions & 9 deletions controller/mater_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ import (

func TestGetCategoryList(t *testing.T) {
router := test.Prepare()
router.GET("/api/master/category", GetCategoryList())
router.GET(APIMasterCategory, GetCategoryList())

req := httptest.NewRequest("GET", "/api/master/category", nil)
req := httptest.NewRequest("GET", APIMasterCategory, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

data := [...]*model.Category{
&model.Category{ID: 1, Name: "技術書"},
&model.Category{ID: 2, Name: "雑誌"},
&model.Category{ID: 3, Name: "小説"},
{ID: 1, Name: "技術書"},
{ID: 2, Name: "雑誌"},
{ID: 3, Name: "小説"},
}

assert.Equal(t, http.StatusOK, rec.Code)
Expand All @@ -31,16 +31,16 @@ func TestGetCategoryList(t *testing.T) {

func TestGetFormatList(t *testing.T) {
router := test.Prepare()
router.GET("/api/master/format", GetFormatList())
router.GET(APIMasterFormat, GetFormatList())

req := httptest.NewRequest("GET", "/api/master/format", nil)
req := httptest.NewRequest("GET", APIMasterFormat, nil)
rec := httptest.NewRecorder()

router.ServeHTTP(rec, req)

data := [...]*model.Format{
&model.Format{ID: 1, Name: "書籍"},
&model.Format{ID: 2, Name: "電子書籍"},
{ID: 1, Name: "書籍"},
{ID: 2, Name: "電子書籍"},
}

assert.Equal(t, http.StatusOK, rec.Code)
Expand Down
43 changes: 16 additions & 27 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
)

// Init is
func Init(e *echo.Echo, config *config.Config) {
if config.Extension.CorsEnabled {
func Init(e *echo.Echo, conf *config.Config) {
if conf.Extension.CorsEnabled {
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowCredentials: true,
AllowOrigins: []string{"*"},
Expand All @@ -35,29 +35,18 @@ func Init(e *echo.Echo, config *config.Config) {
e.HTTPErrorHandler = controller.JSONErrorHandler
e.Use(middleware.Recover())

api := e.Group("/api")
{
book := api.Group("/book")
{
book.GET("/list", controller.GetBookList())
book.GET("/search", controller.GetBookSearch())
book.POST("/new", controller.PostBookRegist())
book.POST("/edit", controller.PostBookEdit())
book.POST("/delete", controller.PostBookDelete())
}

master := api.Group("/master")
{
master.GET("/category", controller.GetCategoryList())
master.GET("/format", controller.GetFormatList())
}

account := api.Group("/account")
{
account.GET("/loginStatus", controller.GetLoginStatus())
account.GET("/loginAccount", controller.GetLoginAccount())
}

api.GET("/health", controller.GetHealthCheck())
}
e.GET(controller.APIBookList, controller.GetBookList())
e.GET(controller.APIBookSearch, controller.GetBookSearch())
e.POST(controller.APIBookRegist, controller.PostBookRegist())
e.POST(controller.APIBookEdit, controller.PostBookEdit())
e.POST(controller.APIBookDelete, controller.PostBookDelete())

e.GET(controller.APIMasterCategory, controller.GetCategoryList())
e.GET(controller.APIMasterFormat, controller.GetFormatList())

e.GET(controller.APIAccountLoginStatus, controller.GetLoginStatus())
e.GET(controller.APIAccountLoginAccount, controller.GetLoginAccount())

e.GET(controller.APIHealth, controller.GetHealthCheck())

}
53 changes: 53 additions & 0 deletions test/request_builder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package test

// RequestBuilder builds request URL.
type RequestBuilder struct {
url string
params map[string]string
}

// NewRequestBuilder is constructor.
func NewRequestBuilder() *RequestBuilder {
return &RequestBuilder{url: "", params: make(map[string]string)}
}

// URL sets request base url.
func (b *RequestBuilder) URL(url string) *RequestBuilder {
b.url = url
return b
}

// Params set a request parameter of the reqest.
func (b *RequestBuilder) Params(name string, value string) *RequestBuilder {
b.params[name] = value
return b
}

// Build builds request url.
func (b *RequestBuilder) Build() *RequestURL {
return &RequestURL{url: b.url, params: b.params}
}

// RequestURL is the element to compose request url.
type RequestURL struct {
url string
params map[string]string
}

// GetRequestURL returns request url builded by request builder.
func (r *RequestURL) GetRequestURL() string {
return r.url + "?" + r.getParams()
}

func (r *RequestURL) getParams() string {
count := 0
result := ""
for key, value := range r.params {
result += key + "=" + value
if count != len(r.params)-1 {
result += "&"
count++
}
}
return result
}

0 comments on commit 40f7011

Please sign in to comment.