使用gorm和sql-mock编写单元测试时遇到的问题

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

Problem writing a unit test using gorm and sql-mock

问题

这是我使用testing、gorm和sql-mock包的函数:

func Test_Create(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Errorf("无法打开模拟的SQL数据库,错误信息:%v", err)
	}
	if db == nil {
		t.Error("db为空")
	}
	if mock == nil {
		t.Error("mock为空")
	}
	defer db.Close()

	pDb, err := gorm.Open(postgres.New(postgres.Config{
		PreferSimpleProtocol: false,
		DriverName:           "postgres",
		Conn:                 db,
	}))
	if err != nil {
		t.Fatalf("gorm打开postgres失败:%v", err)
	}
	student := Student{
		ID:   12345,
		Name: "测试用户",
	}

	mock.ExpectBegin()
	mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO "students" ("id","name") VALUES ($1,$2) RETURNING "id"`)).WithArgs(student.ID, student.Name).WillReturnResult(sqlmock.NewResult(student.ID, 1))
	mock.ExpectCommit()

	err = pDb.Create(student).Error
	if err != nil {
		t.Error("错误信息:", err)
	}
}

我不明白为什么在创建单元测试时会出现错误,就像下面的示例一样,有人可以帮忙吗?

英文:

this is my funckion using package testing, gorm and sql-mock:

func Test_Create(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Errorf("Failed to open mock sql db, got error: %v", err)
	}
	if db == nil {
		t.Error("db is null")
	}
	if mock == nil {
		t.Error("mock is null")
	}
	defer db.Close()

	pDb, err := gorm.Open(postgres.New(postgres.Config{
		PreferSimpleProtocol: false,
		DriverName:           "postgres",
		Conn:                 db,
	}))
	if err != nil {
		t.Fatalf("gorm postgres fatal: %v", err)
	}
	student := Student{
		ID:   12345,
		Name: "Test user",
	}

	mock.ExpectBegin()
	mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO "students" ("id","name") VALUES ($1,$2) RETURNING "id"`)).WithArgs(student.ID, student.Name).WillReturnResult(sqlmock.NewResult(student.ID, 1))
	mock.ExpectCommit()

	err = pDb.Create(student).Error
	if err != nil {
		t.Error("error:", err)
	}
}

I don't understand why I have an error creating a unit test as in the example below, can anyone help?

答案1

得分: 1

好的,我已经解决了这个问题。这是工作的函数:

func Test_Create(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Errorf("无法打开模拟的 SQL 数据库,错误信息:%v", err)
	}
	if db == nil {
		t.Error("db 为空")
	}
	if mock == nil {
		t.Error("mock 为空")
	}
	defer db.Close()

	dialector := postgres.New(postgres.Config{
		DSN:                  "sqlmock_db_0",
		DriverName:           "postgres",
		Conn:                 db,
		PreferSimpleProtocol: true,
	})

	pDb, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		t.Fatalf("gorm postgres 致命错误:%v", err)
	}
	student := Student{
		ID:   12345,
		Name: "测试用户",
	}

	mock.ExpectBegin()
	mock.ExpectQuery(
		regexp.QuoteMeta(`INSERT INTO "students" ("name","id") VALUES ($1,$2) RETURNING "id"`)).
		WithArgs(student.Name, student.ID).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(student.ID))
	mock.ExpectCommit()

	if err = pDb.Create(&student).Error; err != nil {
		t.Errorf("无法插入到 gorm 数据库,错误信息:%v", err)
		t.FailNow()
	}

	err = mock.ExpectationsWereMet()
	if err != nil {
		t.Errorf("未满足期望,错误信息:%v", err)
	}
}
英文:

okay, I've already solved the problem. here's the working func:

func Test_Create(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Errorf("Failed to open mock sql db, got error: %v", err)
	}
	if db == nil {
		t.Error("db is null")
	}
	if mock == nil {
		t.Error("mock is null")
	}
	defer db.Close()

	dialector := postgres.New(postgres.Config{
		DSN:                  "sqlmock_db_0",
		DriverName:           "postgres",
		Conn:                 db,
		PreferSimpleProtocol: true,
	})

	pDb, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		t.Fatalf("gorm postgres fatal: %v", err)
	}
	student := Student{
		ID:   12345,
		Name: "Test user",
	}

	mock.ExpectBegin()
	mock.ExpectQuery(
		regexp.QuoteMeta(`INSERT INTO "students" ("name","id") VALUES ($1,$2) RETURNING "id"`)).
		WithArgs(student.Name, student.ID).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(student.ID))
	mock.ExpectCommit()

	if err = pDb.Create(&student).Error; err != nil {
		t.Errorf("Failed to insert to gorm db, got error: %v", err)
		t.FailNow()
	}

	err = mock.ExpectationsWereMet()
	if err != nil {
		t.Errorf("Failed to meet expectations, got error: %v", err)
	}
}

huangapple
  • 本文由 发表于 2023年1月21日 19:00:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75192805.html
匿名

发表评论

匿名网友

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

确定