samedi 22 août 2020

sqlmock: expectations do not match (being exactly the same queries)

I can't get the expetations to match. I copied and pasted the same query and it doesn't even have any characters that need to be escaped.

I have the following code:

 query := "SELECT id, user_id, name, description, created_at, updated_at FROM products"

 settings := config.GetSettings()

 if limit == 0 {
     limit = settings.MaxElementsPerPagination
 }

 stmt, err := db.Prepare(query)
 if err != nil {
     err = fmt.Errorf("failed to prepare the select products statement: %v", err)
     return
 }
 defer stmt.Close()

 rows, err := stmt.Query()
 if err != nil {
     if errors.Is(err, sql.ErrNoRows) {
         err = fmt.Errorf("failed to select products: %w", errs.ErrNotExistentObject)
         return
     }

     err = fmt.Errorf("failed to select products: %v", err)
     return
 }

 var product models.Product

 for rows.Next() {
     err = rows.Scan(
         &product.ID,
         &product.UserID,
         &product.Name,
         &product.Description,
         &product.CreatedAt,
         &product.UpdatedAt,
     )
     if err != nil {
         err = fmt.Errorf("failed to scan product: %v", err)
         return
     }

     products = append(products, product)
 }

And this is my test code:

    // Setup database
    db, mock, err := sqlmock.New()
    assert.Nil(t, err)

    database.New(db)
   
   // Without Regex
    mock.ExpectQuery("SELECT id, user_id, name, description, created_at, updated_at FROM products")
   // With Regex
    // mock.ExpectQuery("SELECT (.+) FROM `products`")

   // I try it with rows

   // rows := sqlmock.NewRows([]string{"id", "user_id", "name", "description", "created_at", "updated_at"})

   // rows.AddRow(1, 1, "TV Monitor", "Monitor for TV", time.Now(), time.Now())
   // rows.AddRow(2, 1, "Router", "Awesome router", time.Now(), nil)

   // Without Regex
    // mock.ExpectQuery("SELECT id, user_id, name, description, created_at, updated_at FROM products").
   //     WillReturnRows(rows)
   // With Regex
   // mock.ExpectQuery("SELECT (.+) FROM `products`").
   //     WillReturnRows(rows)

    // Setup server
    e := echo.New()
    req := httptest.NewRequest(http.MethodGet, "/", nil)
    req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)

    if assert.NoError(t, handlers.GetProducts(c)) {
        assert.Equal(t, http.StatusOK, rec.Code)
        assert.Equal(t, "pong", rec.Body.String())
    }

    assert.Nil(t, mock.ExpectationsWereMet())

I've looked for all kinds of tutorials but there aren't that many sqlmock examples. I've never used it and don't understand why this doesn't work.

Aucun commentaire:

Enregistrer un commentaire