I'm setting service_test.go
for service.go
.
In service.go
, method is called from dao.go
.
So I need to mock this dao method.
But I'm not sure how to code this mock method.
Here is the repository structure.
article
├ client
├ api
│ ├ main.go
│ ├ contoroller
│ │ └ contoroller.go
│ ├ service
│ │ └ service.go
│ ├ dao
│ │ └ dao.go
│ ├ go.mod
│ ├ go.sum
│ └ Dockerfile
├ nginx
└ docker-compose.yml
service.go
func GetArticleService(db *sql.DB) []util.Article {
var articles []util.Article
// I want to mock dao.GetArticleDao(db)
results := dao.GetArticleDao(db)
article := util.Article{}
for results.Next() {
err := results.Scan(&article.ID, &article.UUID, &article.TITLE, &article.CONTENT)
if err != nil {
panic(err.Error())
} else {
articles = append(articles, article)
}
}
return articles
}
service_test.go
func TestGetArticleService(t *testing.T) {
//mock db
db, _, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
//make expected value
var expectedArticles []util.Article
expectedArticle1 := util.Article{
ID: 1,
UUID: "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c",
TITLE: "test",
CONTENT: "test",
}
expectedArticles = append(expectedArticles, expectedArticle1)
expectedArticle2 := util.Article{
ID: 2,
UUID: "844bc620-7336-41a3-9cb4-552a0024ff1c",
TITLE: "test2",
CONTENT: "test2",
}
expectedArticles = append(expectedArticles, expectedArticle2)
//check whether expected value and GetArticleService(db) is equal.
//Since GetArticleService(db) is executed, I want to mock dao.GetArticleDao(db)
assert.Equal(t, expectedArticles, GetArticleService(db))
}
I want to mock dao.GetArticleDao(db)
in service.go
to pass test in service_test.go
.
But I'm not sure how to mock this code.