DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.02k stars 406 forks source link

sqlmock does not produce an error on unexpected query #283

Closed SamiAlsubhi closed 2 years ago

SamiAlsubhi commented 2 years ago

In this test, there is a query that gets executed when this API is called. This query is to select a user. The interesting thing when I comment this query out from the test, which means it is not expected, mock.ExpectationsWereMet it does not give any error! am I missing something on how this mock works, isn't supposed to give an error if a query is executed without being expected?

func Test(t *testing.T) {

    s := suite.Start(t)

    s.Mock.MatchExpectationsInOrder(true)

    phone := s.GetRandomPhone()
    otp_code := s.GetRandomCode()

    s.Mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "otps" WHERE phone = $1 AND "otps"."deleted_at" IS NULL`)).
        WithArgs(phone).
        WillReturnRows(sqlmock.NewRows([]string{"id", "phone", "code", "created_at", "updated_at", "deleted_at"}).
            AddRow(1, phone, otp_code, time.Now(), time.Now(), nil))

    // This query gets actually called but when I comment it out (meaning not expected)
    s.Mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "user" WHERE phone = $1 AND "user"."deleted_at" IS NULL ORDER BY "user"."id" LIMIT 1`)).
        WithArgs(phone)

    code, response := s.POST(t, "/api/auth/verify-otp/user", nil, &gin.H{"phone": phone, "code": otp_code})

    assert.Equal(t, 200, code)
    require.Contains(t, response, "access_token")
    require.Contains(t, response, "refresh_token")
    assert.Equal(t, response["id"], float64(0))

    //this does not give any error
    require.NoError(t, s.Mock.ExpectationsWereMet())
}
SamiAlsubhi commented 2 years ago

Ok, now I understand, not all executed queries have to be expected. mock.ExpectationsWereMet() is specifically for explicitly stated as so. That is being said, sqlmock will highlighted any not expected queries if test fails by any other means.