使用存储过程模拟postgresql

时间:2017-09-20 00:30:13

标签: database postgresql go

我一直在浏览https://github.com/DATA-DOG/go-sqlmock的测试文件,以找出如何创建存储过程以进行模拟。我有:

_, err = db.Exec(`
    CREATE OR REPLACE FUNCTION val() RETURNS INT AS 
        $$ SELECT 1; $$ 
    LANGUAGE sql;   
`)

if err != nil {
    t.Fatal(err)
}

我明白了:

all expectations were already fulfilled, call to exec 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;' query with args [] was not expected

相反,如果我用

尝试
        mock.ExpectExec(`
            CREATE OR REPLACE FUNCTION val() RETURNS INT AS
                $$ SELECT 1; $$
            LANGUAGE sql;
        `,
        ).WillReturnResult(sqlmock.NewResult(0, 0))

        if err := mock.ExpectationsWereMet(); err != nil {
            t.Fatal(err)
        }

我明白了:

there is a remaining expectation which was not matched: ExpectedExec => expecting Exec which:
              - matches sql: 'CREATE OR REPLACE FUNCTION val() RETURNS INT AS $$ SELECT 1; $$ LANGUAGE sql;'
              - is without arguments
              - should return Result having:
                  LastInsertId: 0
                  RowsAffected: 0

我对如何设置基本存储过程感到困惑。

1 个答案:

答案 0 :(得分:2)

sqlmock库非常适用于此。

但请注意,ExpectExec会收到正则表达式以便匹配:

// ExpectExec expects Exec() to be called with sql query
// which match sqlRegexStr given regexp.
// the *ExpectedExec allows to mock database response
ExpectExec(sqlRegexStr string) *ExpectedExec

您正在向该函数发送您希望收到的确切字符串,而不会进行任何转义。

要转义字符串,请添加以下内容:

import (
   "regexp"
)

然后在添加期望时,请转义字符串(注意regexp.QuoteMeta):

mock.ExpectExec(regexp.QuoteMeta(`
    CREATE OR REPLACE FUNCTION val() RETURNS INT AS
        $$
        SELECT 1;
        $$
    LANGUAGE sql;
`),
).WillReturnResult(sqlmock.NewResult(0, 0))

这样,转义的正则表达式将匹配您的exec命令。