du16178 2018-08-24 20:12
浏览 227
已采纳

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

In trying to test the following func:

//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
}

I make use of the sqlmock library to mock database actions. This has served me well thus far, but is causing regressions when I start piling on test cases.

Setup

My test setup is thus:

// 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()

Test functions

To create this MVCE, I reduced it down to two tests. Both work when the other is commented out:

First Test

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()

    })

Second Test

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))
        }
    })

Problem

When I make sure that neither one is commented out, I get chaos. The message I get is thus:

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:"

\tC:/Go/src/runtime/debug/stack.go:24 +0xae
ezsoft/apiserver_sdk/utilities/utilityCore.GetCleanStack(0xc042069470, 0x3, 0x3, 0x3, 0xc0420db8e8)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/utilities/utilityCore/utilityCore.go:56 +0x3b
ezsoft/apiserver_sdk/db.beginTrans(0xc04204d360, 0x0, 0x0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:365 +0x100
ezsoft/apiserver_sdk/db.Transaction(0xc04204d360, 0x821690, 0x0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:443 +0x3f
ezsoft/apiserver_sdk/db.TestTransaction.func2(0xc0421363c0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU_test.go:1851 +0x75
testing.tRunner(0xc0421363c0, 0xc0420e48a0)
\tC:/Go/src/testing/testing.go:777 +0xd7
created by testing.(*T).Run
\tC:/Go/src/testing/testing.go:824 +0x2e7
"}

                                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) "

\tC:/Go/src/runtime/debug/stack.go:24 +0xae
ezsoft/apiserver_sdk/utilities/utilityCore.GetCleanStack(0xc042069470, 0x3, 0x3, 0x3, 0xc0420db8e8)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/utilities/utilityCore/utilityCore.go:56 +0x3b
ezsoft/apiserver_sdk/db.beginTrans(0xc04204d360, 0x0, 0x0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:365 +0x100
ezsoft/apiserver_sdk/db.Transaction(0xc04204d360, 0x821690, 0x0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU.go:443 +0x3f
ezsoft/apiserver_sdk/db.TestTransaction.func2(0xc0421363c0)
\tD:/dev2017/GO/src/ezsoft/apiserver_sdk/db/dbConnectionsU_test.go:1851 +0x75
testing.tRunner(0xc0421363c0, 0xc0420e48a0)
\tC:/Go/src/testing/testing.go:777 +0xd7
created by testing.(*T).Run
\tC:/Go/src/testing/testing.go:824 +0x2e7
"
                                 })
                Test:           TestTransaction/WantErrorFromCallback

It's acting like the calls to Begin were never expected, but in both cases, literally the first line of code is mock.ExpectBegin()!

I suspect it may have to deal with deferred code, both in the func under test and necessarily in my test code, but I don't know how to control for that. Furthermore, I'm not sure my suspicion is right.

  • 写回答

1条回答 默认 最新

  • dousunle5801 2018-08-28 15:18
    关注

    Wow, I feel silly.

    The issue was with synchronization, and apparently, stale mock state.

    The solution

    Instead of the standard approach, I whipped out testify's suites, and refactored the tests themselves to be suite methods, which assert that ExpectationsWereMet() in the deferred func. The expectations (ExpectCommit, ExpectRollback, ...) are the first things to happen.

    Can't believe I just bountied this question over something so simple.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?