来自多个导致错误失败的测试案例的类似sqlmock期望

时间:2018-08-24 20:12:56

标签: go mocking

在尝试测试以下功能时:

//Transaction Begins a sql transaction.
func Transaction(db *sql.DB, txFunc func(*sql.Tx) *errors.ErrorSt) (retErrSt *errors.ErrorSt) {
    retErrSt = nil
    tx, retErrSt := beginTrans(db)
    if retErrSt != nil {
        return retErrSt
    }

    defer func() {
        if p := recover(); p != nil {
            tx.Rollback()
            panic(p) // re-throw panic after Rollback
        } else if retErrSt != nil {
            tx.Rollback()
        } else {
            if err := tx.Commit(); err != nil {
                retErrSt = errors.Database().AddDetails(err.Error())
            }
        }
    }()
    retErrSt = txFunc(tx)
    return retErrSt
}

我利用sqlmock库来模拟数据库操作。到目前为止,这对我非常有用,但是当我开始堆积测试用例时,这会导致回归。

设置

因此,我的测试设置是:

// database mock/stub setup
    db, mock, err := sqlmock.New()
    if !assert.Nilf(t,
        err,
        "Error on trying to start up a stub database connection") {
        t.Fatal()
    }
    defer db.Close()

测试功能

要创建此MVCE,我将其简化为两个测试。当对方被注释掉时,两者都可以工作:

首次测试

t.Run("WantCommitError", func(t *testing.T) {
        // define sql behavior
        mock.ExpectBegin()

        err := Transaction(db,
            func(tx *sql.Tx) *errors.ErrorSt {
                return nil
            })

        defer func() {
            mock.ExpectCommit().
                WillReturnError(goErrors.New("test commit error"))
            assert.Equal(t,
                string(errors.ACDatabase),
                err.Code)
        }()

        mock.ExpectationsWereMet()

    })

第二次测试

t.Run("WantErrorFromCallback", func(t *testing.T) {
        mock.ExpectBegin()

        err := Transaction(db,
            func(tx *sql.Tx) *errors.ErrorSt { return new(errors.ErrorSt) })

        defer func() {
            mock.ExpectRollback()
        }()
        mock.ExpectationsWereMet()

        if !assert.Equal(t, new(errors.ErrorSt), err) {
            t.Error(err.ToString(false))
        }
    })

问题

当我确保没有人被注释掉时,我会感到混乱。因此,我得到的消息是:

Error Trace:    dbConnectionsU_test.go:1859
                Error:          Not equal: 
                                expected: &errors.ErrorSt{Code:"", Message:"", Scope:0, Severity:0, Details:errors.LoggerDetails(nil), InnerError:(*errors.ErrorSt)(nil), Stack:""}
                                actual  : &errors.ErrorSt{Code:"db", Message:"", Scope:0, Severity:0, Details:errors.LoggerDetails{"call to database transaction Begin, was not expected, next expectation is: ExpectedCommit => expecting transaction Commit, which should return error: test commit error"}, InnerError:(*errors.ErrorSt)(nil), Stack:"\n\n\tC:/Go/src/runtime/debug/stack.go:24 +0xae\nezsoft/apiserver_sdk/utilities/utilityCore.GetCleanStack(0xc042069470, 0x3, 0x3, 0x3, 0xc0420db8e8)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/utilities/utilityCore/utilityCore.go:56 +0x3b\nezsoft/apiserver_sdk/db.beginTrans(0xc04204d360, 0x0, 0x0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:365 +0x100\nezsoft/apiserver_sdk/db.Transaction(0xc04204d360, 0x821690, 0x0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:443 +0x3f\nezsoft/apiserver_sdk/db.TestTransaction.func2(0xc0421363c0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU_test.go:1851 +0x75\ntesting.tRunner(0xc0421363c0, 0xc0420e48a0)\n\tC:/Go/src/testing/testing.go:777 +0xd7\ncreated by testing.(*T).Run\n\tC:/Go/src/testing/testing.go:824 +0x2e7\n"}

                                Diff:
                                --- Expected
                                +++ Actual
                                @@ -1,3 +1,3 @@
                                 (*errors.ErrorSt)({
                                - Code: (string) "",
                                + Code: (string) (len=2) "db",
                                  Message: (string) "",
                                @@ -5,5 +5,7 @@
                                  Severity: (errors.Severity) 0,
                                - Details: (errors.LoggerDetails) <nil>,
                                + Details: (errors.LoggerDetails) (len=1) {
                                +  (string) (len=167) "call to database transaction Begin, was not expected, next expectation is: ExpectedCommit => expecting transaction Commit, which should return error: test commit error"
                                + },
                                  InnerError: (*errors.ErrorSt)(<nil>),
                                - Stack: (string) ""
                                + Stack: (string) (len=788) "\n\n\tC:/Go/src/runtime/debug/stack.go:24 +0xae\nezsoft/apiserver_sdk/utilities/utilityCore.GetCleanStack(0xc042069470, 0x3, 0x3, 0x3, 0xc0420db8e8)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/utilities/utilityCore/utilityCore.go:56 +0x3b\nezsoft/apiserver_sdk/db.beginTrans(0xc04204d360, 0x0, 0x0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:365 +0x100\nezsoft/apiserver_sdk/db.Transaction(0xc04204d360, 0x821690, 0x0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:443 +0x3f\nezsoft/apiserver_sdk/db.TestTransaction.func2(0xc0421363c0)\n\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU_test.go:1851 +0x75\ntesting.tRunner(0xc0421363c0, 0xc0420e48a0)\n\tC:/Go/src/testing/testing.go:777 +0xd7\ncreated by testing.(*T).Run\n\tC:/Go/src/testing/testing.go:824 +0x2e7\n"
                                 })
                Test:           TestTransaction/WantErrorFromCallback

这就像从未期望过对Begin的调用一样,但是在两种情况下,实际上第一行代码都是mock.ExpectBegin()

我怀疑在测试中的功能中以及在我的测试代码中都可能必须处理defer红色代码,但是我不知道该如何控制。此外,我不确定我的猜想是否正确。

1 个答案:

答案 0 :(得分:1)

哇,我觉得很傻。

问题在于同步,显然是过时的模拟状态。

解决方案

我没有采用标准方法,而是淘汰了testify's suites,并将测试本身重构为套件方法,这些方法断言ExpectationsWereMet()在红色函数中是defer。期望(ExpectCommitExpectRollback,...)是首先发生的事情。

不敢相信我只是因为这么简单的事情而悬赏这个问题。