使用sqlmock进行DB模拟在测试Gin/GORM API时不起作用吗?

huangapple go评论80阅读模式
英文:

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.

https://github.com/keploy/keploy

huangapple
  • 本文由 发表于 2022年4月11日 21:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/71828790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定