0

我有一个函数,旨在使用表值参数和过程将大量元素插入 MSSQL 数据库。

func (requester *Requester) doQuery(ctx context.Context, dtos interface{}) error {
    conn, err := requester.conn.Conn(ctx)
    if err != nil {
        return err
    }

    defer func() {
        if clErr := conn.Close(); clErr != nil {
            err = clErr
        }
    }()

    tx, err := conn.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: false})
    if err != nil {
        return err
    }

    defer func() {
        if p := recover(); p != nil {
            tx.Rollback()
            panic(p)
        } else if err != nil {
            tx.Rollback()
        } else {
            tx.Commit()
    }()

    param := sql.Named("TVP", mssql.TVP{
        TypeName: "MyTypeName",
        Value:    dtos,
    })

    return tx.ExecContext(ctx, "EXEC [dbo].[usp_InsertConsumption] @TVP", param)
}

我为这个函数写的测试包括在下面(注意它取决于银杏和gomega):

Describe("SQL Tests", func() {

    It("AddConsumption - No failures - Added", func() {

        db, mock, _ := sqlmock.New()
        requester := Requester{conn: db}
        defer db.Close()

        mock.ExpectBegin()
        mock.ExpectExec(regexp.QuoteMeta("EXEC [dbo].[usp_InsertConsumption] @TVP")).
            WithArgs("").WillReturnResult(sqlmock.NewResult(1, 1))
        mock.ExpectExec(regexp.QuoteMeta("EXEC [dbo].[usp_InsertTags] @TVP")).
            WithArgs("").WillReturnResult(sqlmock.NewResult(1, 1))
        mock.ExpectCommit()

        err := requester.doQuery(context.TODO(), generateData())
        Expect(err).ShouldNot(HaveOccurred())
        Expect(mock.ExpectationsWereMet()).ShouldNot(HaveOccurred())
    })
})

现在,这段代码是为 MySQL 上下文编写的,自从我将代码移植到 MSSQL 后,我遇到了一个特殊的错误:

sql: converting argument with name \"TVP\" type: unsupported type mssql.TVP, a struct

似乎 sqlmock 正在尝试调用ConvertValue无效的 TVP 对象。那么,如何让 sqlmock 正确处理这个值,以便我可以围绕查询进行单元测试?

4

1 回答 1

0

我在这里发现的是 sqlmock 有一个名为 的函数ValueConverterOption,当它提供自定义driver.ValueConverter接口时。每次调用ConvertValue. 如果您想在ExecContext函数接收到非标准参数时测试它,TVP在这种情况下是 a,那么您可以使用此函数将自定义转换逻辑注入 sqlmock。

type mockTvpConverter struct {}

func (converter *mockTvpConverter) ConvertValue(raw interface{}) (driver.Value, error) {

    // Since this function will take the place of every call of ConvertValue, we will inevitably
    // the fake string we return from this function so we need to check whether we've recieved
    // that or a TVP. More extensive logic may be required
    switch inner := raw.(type) {
    case string:
        return raw.(string), nil
    case mssql.TVP:

        // First, verify the type name
        Expect(inner.TypeName).Should(Equal("MyTypeName"))

        // VERIFICATION LOGIC HERE

        // Finally, return a fake value that we can use when verifying the arguments
        return "PASSED", nil
    }

    // We had an invalid type; return an error
    return nil, fmt.Errorf("Invalid type")
}

这意味着,测试然后变为:

Describe("SQL Tests", func() {

    It("AddConsumption - No failures - Added", func() {

        db, mock, _ := sqlmock.New(sqlmock.ValueConverterOption(&mockTvpConverter{}))
        requester := Requester{conn: db}
        defer db.Close()

        mock.ExpectBegin()
        mock.ExpectExec(regexp.QuoteMeta("EXEC [dbo].[usp_InsertConsumption] @TVP")).
            WithArgs("PASSED").WillReturnResult(sqlmock.NewResult(1, 1))
        mock.ExpectExec(regexp.QuoteMeta("EXEC [dbo].[usp_InsertTags] @TVP")).
            WithArgs("PASSED").WillReturnResult(sqlmock.NewResult(1, 1))
        mock.ExpectCommit()

        err := requester.doQuery(context.TODO(), generateData())
        Expect(err).ShouldNot(HaveOccurred())
        Expect(mock.ExpectationsWereMet()).ShouldNot(HaveOccurred())
    })
})
于 2020-11-25T10:15:19.047 回答