我能够成功模拟查询以从一个表中进行选择,如下所示:
sqlMock.ExpectQuery("^SELECT DISTINCT (.+) FROM myTable1, myTable2").
WillReturnRows(myResultRows)
但是我无法模拟以下查询来检查我的postgres数据库中是否存在该表:
SELECT EXISTS
( SELECT 1
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'myTable3' );
以下各项的组合:
existsRows := sqlmock.NewRows([]string{"exists"}).
AddRow(true)
AND
slMock.ExpectQuery("^SELECT EXISTS").
WillReturnRows(existsRows)
我也尝试了模拟SELECT 1
,但得到了完全相同的错误:
time="2019-09-27T15:49:41-07:00" level=panic msg="db query" error="call to Query 'SELECT EXISTS\n\t\t( SELECT 1\n\t\tFROM information_schema.tables\n\t\tWHERE table_schema = 'public'\n\t\t AND table_name = 'myTable3' );' with args [], was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which......
我正在使用的包裹:
import (
"database/sql"
"db"
"os"
"testing"
// not explicitly called
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/lib/pq"
"github.com/DATA-DOG/go-sqlmock"
"github.com/sirupsen/logrus"
)
任何想法或指示都值得赞赏。我在互联网上找不到相关示例
答案 0 :(得分:0)
我不确定,但认为问题出在您的查询缩进中,请尝试删除换行符或查询SELECT EXISTS
( SELECT 1
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'myTable3' );
中的列表
赞这个SELECT EXISTS( SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'myTable3' );
答案 1 :(得分:0)
实际上,
sqlMock.ExpectQuery("SELECT EXISTS \\( SELECT 1 FROM information_schema\\.tables WHERE table_schema = 'public' AND table_name = 'myTable3' \\);").
WillReturnRows(existsRows)
成功了!
我还使用了regex101.com
提示是直接期待下一个查询。因此,我们知道它根本没有读过这一本书。我的同事指出了:)