mysql - 如何测试mysql的insert方法

标签 mysql go testing go-sqlmock

我正在 Go 中设置测试。我使用 go-sqlmock 来测试 mysql 连接。现在我尝试测试 mysql insert 逻辑。但是出现错误。
我想知道如何解决这个错误。

server side: golang
db: mysql
web framework: gin

dao.go

func PostDao(db *sql.DB, article util.Article, uu string) {
    ins, err := db.Prepare("INSERT INTO articles(uuid, title,content) VALUES(?,?,?)")
    if err != nil {
        log.Fatal(err)
    }
    ins.Exec(uu, article.TITLE, article.CONTENT)
}

dao_test.go

func TestPostArticleDao(t *testing.T) {
    db, mock, err := sqlmock.New()

    if err != nil {
        t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
    }

    defer db.Close()

    mock.ExpectExec("^INSERT INTO articles*").
        WithArgs("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "test", "test").
        WillReturnResult(sqlmock.NewResult(1, 1))

    article := util.Article{
        ID:      1,
        TITLE:   "test",
        CONTENT: "test",
    }

    PostDao(db, article, "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c")

    if err := mock.ExpectationsWereMet(); err != nil {
        t.Errorf("there were unfulfilled expections: %s", err)
    }
}

我希望 go test -v 运行没有错误。
但实际情况并非如此。
这是错误。

=== RUN   TestPostArticleDao
2019/08/31 00:08:11 call to Prepare statement with query 'INSERT INTO articles(uuid, title,content) VALUES(?,?,?)', was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which:
  - matches sql: 'INSERT INTO articles(uuid, title,content) VALUES(?,?,?)'
  - is with arguments:
    0 - bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c
    1 - test
    2 - test
  - should return Result having:
      LastInsertId: 1
      RowsAffected: 1
exit status 1
FAIL    article/api/dao 0.022s

最佳答案

正如@Flimzy建议的那样,需要先设置ExpectPrepare
所以我以这种方式更改了dao_test.go:

    prep := mock.ExpectPrepare("^INSERT INTO articles*")

    prep.ExpectExec().
        WithArgs("bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "test", "test").
        WillReturnResult(sqlmock.NewResult(1, 1))

关于mysql - 如何测试mysql的insert方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729947/

相关文章:

php - 如何使用mysql和php进行排名

mysql - 将多列 MySql 记录转换为响应式显示

MySQL 忘记了自动为外键创建索引?

go - 读取任意数量的输入标准输入

node.js - 如何构建用于测试的 meteor 应用程序

ruby - 你如何在 Sinatra 中运行测试?

testing - 如何使用马拉松测试工具(MarathonITE)从命令行运行少量测试用例或测试套件?

asp.net - .net mvc (MySQL) 的 sessionState 问题

MySQL - GORM 外键返回空对象

go - 序列化为JSON动态结构