英文:
DB mock using sqlmock not working for testing Gin/GORM API?
问题
我有一个使用Gin
编写的API,使用GORM
进行ORM操作。当使用真实的数据库并从Web浏览器访问API URL时,API运行得非常好。但是,我无法通过模拟的单元测试来通过:
最后的if
语句被触发。got
的长度实际上是0。然而,如果我尝试在服务器使用真实数据库的情况下从浏览器调用与GetUsersWrapper
相关的API端点,一切都按预期工作。
我怀疑要么sqlmock.NewRows
没有创建行,以便gormDB
可以看到,要么我没有正确测试GetUsersWrapper
的响应。我如何正确地对gin
API进行单元测试?
英文:
I've an API written using Gin
that uses GORM
for ORM. The API works perfectly fine when using a real DB and accessing the API URL from the web browser. But I can't get a mocked unit test to pass:
func TestRespForGetUsersHandlerWithSomeUsers(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal("can't create mock db")
}
defer db.Close()
sqlmock.NewRows(
[]string{"id", "name", "username"},
).
AddRow(1, "Abhishek Kumar", "abhishek")
w := httptest.NewRecord()
c, _ := gin.CreateTestContext(w)
postgresDB := postgres.New(postgres.Config{Conn: db})
gormDB, err := gorm.Open(postgresDB, &gorm.Config{})
if err != nil {
t.Fatal("can't create gormDB")
}
api.GetUsersWrapper(gormDB)(c)
if w.Code != http.StatusOK {
t.Errorf("Expected status code to be %d but got %d", http.StatusOK, w.Code)
}
var got []models.User
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("Can't unmarshal response body: %s", err)
}
if len(got) != 1 {
t.Errorf("Expected response to be 1 item but got %d items", len(got))
}
}
The last if
-statement gets triggered. The length of got
is actually 0. However, if I try calling the API endpoint associated with GetUsersWrapper
from a browser (while the server is using a real DB), everything works as expected.
I suspect that either sqlmock.NewRows
is not creating the rows such that it'll be visible to gormDB
or I'm not testing the response from GetUsersWrapper
properly. How can I unit test a gin
API correctly?
答案1
得分: 1
如果你愿意尝试另一种方法,你可以使用 keploy 来对你的 gin API 进行单元测试。它是一个开源工具,也支持 GORM。
https://github.com/keploy/keploy
英文:
If you're willing to try an alternate approach, you can unit test your gin APIs using keploy. It's open-source and also supports GORM.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论