简体   繁体   中英

Go sqlmock SELECT missing expected query

Go here. Trying to figure out how to use SQL mock v2 .

Here's my interface:

type OrderPersister interface {
    FetchOrderById(string) (*Order, error)
}

And my implementation of that interface:

type DbPersister struct {
    Config config.DbConfig
    GormDB *gorm.DB
}

func (op DbPersister) FetchOrderById(orderId string) (*Order, error) {
    Order := &Order{}

    orderUuid, err := uuid.Parse(orderId)
    if err != nil {
        return nil, err
    }

    if err := op.GormDB.Table("orders").
        Select(`orders.order_id,
            orders.user_id,
            orders.quantity,
            orders.status
            addresses.line_1,
            users.email`).
        Joins("join addresses on addresses.address_id = orders.address_id").
        Joins("join users on users.user_id = orders.user_id").
        Where("orders.order_id = ?", orderUuid).
        First(Order).Error; err != nil {
        return nil, err
    }

    return Order, nil
}

And my unit test (including setup/init):

import (
    "database/sql"
    "testing"

    "github.com/google/uuid"
    "github.com/jinzhu/gorm"
    "github.com/stretchr/testify/require"
    "github.com/stretchr/testify/suite"
    "gopkg.in/DATA-DOG/go-sqlmock.v2"
)

type Suite struct {
    suite.Suite
    DB   *gorm.DB
    mock sqlmock.Sqlmock

    dbPersister OrderPersister
}

func (s *Suite) SetupSuite() {
    var (
        db  *sql.DB
        err error
    )

    db, s.mock, err = sqlmock.New()
    require.NoError(s.T(), err)

    s.DB, err = gorm.Open("postgres", db)
    require.NoError(
        s.T(), err)

    s.DB.LogMode(true)

    s.dbPersister = DbPersister{
        Config: config.DbConfig{
            DbHost:     "",
            DbPort:     "",
            DbName:     "",
            DbUsername: "",
            DbPassword: "",
        },
        GormDB: s.DB,
    }
}

func (s *Suite) BeforeTest(_, _ string) {
    var (
        db  *sql.DB
        err error
    )

    db, s.mock, err = sqlmock.New()
    require.NoError(s.T(), err)

    s.DB, err = gorm.Open("postgres", db)
    require.NoError(s.T(), err)

    s.DB.LogMode(true)
}

func (s *Suite) AfterTest(_, _ string) {
    require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
    suite.Run(t, new(Suite))
}

func (s *Suite) TestFetchOrderById() {

  // given
    orderId := uuid.New()
  quantity := 1
  status := "ready"
    line1 := "201"
  email := "jsmith@example.com"

  // s.mock.ExpectBegin()
    s.mock.ExpectQuery(`SELECT`).
        WillReturnRows(sqlmock.NewRows([]string{"orders.order_id","orders.user_id","orders.quantity","orders.status",
                "addresses.line_1","user_logins.email"}).
            AddRow(sqlmock.AnyArg(), sqlmock.AnyArg(), quantity, status, totalExclTax, shippingExclTax,
                totalTaxAmt, line1, state, zip, locality, upc, email, firstName, lastName))
    _, err := s.dbPersister.FetchOrderById(orderId.String())
  s.mock.ExpectCommit()
    require.NoError(s.T(), err)
}

When this runs the test fails for the following reason:

--- FAIL: TestInit (0.00s)
  --- FAIL: TestInit/TestFetchOrderById (0.00s)
    db_test.go:67: 
        Error Trace:    db_test.go:67
                                suite.go:137
                                panic.go:969
                                rows.go:134
                                db_test.go:99
        Error:          Received unexpected error:
                        there is a remaining expectation which was not matched: ExpectedQuery => expecting Query, QueryContext or QueryRow which:
                          - matches sql: 'SELECT'
                          - is without arguments
        Test:           TestInit/TestFetchOrderById

All I'm trying to do is confirm that the GormDB instance was queried with the SELECT statement specified in the FetchOrderById function.

Does anybody know what I need to do to achieve this and get the test to pass?

我决定转而使用 Java(没有双关语)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM