0

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

Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66
  • Can you post the code/pseudocode of what you trying to test? – Haril Satra Jan 26 '22 at 20:01
  • I think I got it wrong on how this package works. It only compares the explicitly expected queries. If other unexpected queries get executed. They result in an sql error. When I comment out that query, the sql error is quietly handled by the software giving out a similar outcome. Now I get it. – Sami Al-Subhi Jan 27 '22 at 05:28

0 Answers0