Sobes.tech
Junior — Middle

How did you perform testing and verification of the correctness of the executed requests?

sobes.tech AI

Answer from AI

For testing and verifying the correctness of executed queries in Go, I usually apply the following methods:

  • Unit tests: Use the testing package to write tests that check the correctness of query formation and execution.
  • Database mocking: With libraries like sqlmock, you can simulate database behavior and verify that queries are formed correctly and processed as expected.
  • Logging: Enable SQL query logging for debugging and analysis.
  • Result verification: Compare the obtained data with expected data to ensure correctness.

Example of a simple test using sqlmock:

import (
    "database/sql"
    "testing"
    "github.com/DATA-DOG/go-sqlmock"
)

func TestGetUserByID(t *testing.T) {
    db, mock, err := sqlmock.New()
    if err != nil {
        t.Fatalf("error opening stub database: %s", err)
    }
    defer db.Close()

    rows := sqlmock.NewRows([]string{"id", "name"}).AddRow(1, "John")
    mock.ExpectQuery("SELECT id, name FROM users WHERE id = ?").WithArgs(1).WillReturnRows(rows)

    user, err := GetUserByID(db, 1)
    if err != nil {
        t.Errorf("unexpected error: %s", err)
    }
    if user.Name != "John" {
        t.Errorf("expected name John, got %s", user.Name)
    }

    if err := mock.ExpectationsWereMet(); err != nil {
        t.Errorf("there were unfulfilled expectations: %s", err)
    }
}

This approach ensures that queries are formed and processed correctly without the need to connect to a real database.

How did you perform testing and verification of the… - sobes.tech