来自多个导致错误失败的测试案例的类似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.

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.