使用go-sqlmock在golang中模拟sql.max()函数。

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

Mocking sql.max() in golang using go-sqlmock

问题

我正在寻找在我的代码中模拟这个查询的方法("select max(a) from public.abc where id = %d")。

我模拟这行代码的方式是:

maxOfA := 1
maxOfARows := sqlmock.NewRows([]string{"a"}).AddRow(maxOfA)
suite.mock.ExpectQuery("select max(a) from public.abc co where id = $1").WithArgs(1).WillReturnRows(maxOfARows)

但是我看到了这个错误:

Error:
    Query: could not match actual sql: "select max(a) from public.abc where id = 1" with
        expected regexp "select max(a) from public.abc where id = 1"

如何正确地模拟包含max()这样的SQL函数呢?

英文:

I am looking to mock up this query in my code ("select max(a) from public.abc where id = %d")

The way I am mocking this line is

maxOfA := 1
maxOfARows := sqlmock.NewRows([]string{"a"}).AddRow(maxOfA)
suite.mock.ExpectQuery("select max(a) from public.abc co where id = \\\").WithArgs(1).WillReturnRows(maxOfARows)

And I am seeing this error

Error:
	Query: could not match actual sql: "select max(a) from public.abc where id = 1" with
		expected regexp "select max(a) from public.abc where id = 1"

What is the right way to mock the max() such sql functions

答案1

得分: 2

我的错误是没有将模拟查询包裹在(regexp.QuoteMeta())中。将查询包裹在quotemeta中确实解决了我的问题。
参考:https://pkg.go.dev/regexp#QuoteMeta

我不会删除这篇帖子,希望它能帮助像我一样的人。

英文:

My mistake was that i wasnt wrapping up my mock query within (regexp.QuoteMeta()). wrapping up the query within the quotemeta did resolve my issue
Reference: https://pkg.go.dev/regexp#QuoteMeta

Not deleting this post hoping it to help someone like me.

huangapple
  • 本文由 发表于 2023年1月17日 07:41:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75140743.html
匿名

发表评论

匿名网友

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

确定