Last active
June 27, 2024 19:33
-
-
Save vuon9/c9de3e55d69fe4dd1a8ecf68c52802d3 to your computer and use it in GitHub Desktop.
Unit testing with SQLBoiler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package services | |
import ( | |
"database/sql" | |
"reflect" | |
"regexp" | |
"testing" | |
"github.com/DATA-DOG/go-sqlmock" | |
"github.com/volatiletech/sqlboiler/boil" | |
) | |
func testSqlBoilerWithMock(t *testing.T) { | |
// Mock DB instance by sqlmock | |
db, mock, err := sqlmock.New() | |
if err != nil { | |
t.Fatalf("an error '%s' was not expected", err) | |
} | |
// Inject mock instance into boil. | |
oldDB := boil.GetDB() | |
defer func() { | |
db.Close() | |
boil.SetDB(oldDB) | |
}() | |
boil.SetDB(db) | |
// Create mock data with specific columns | |
mockShipperRows := sqlmock.NewRows([]string{"id", "column_name"}).AddRow(1, 123) | |
// Use regexp to avoid comparing query failed | |
mockQueryFindShipper := regexp. | |
QuoteMeta("SELECT * FROM `objects` WHERE (column_name=?) AND (`objects`.deleted_at is null) LIMIT 1;") | |
// Mock a data | |
mock.ExpectQuery(mockQueryFindShipper).WithArgs(123). | |
WillReturnRows(mockShipperRows). | |
RowsWillBeClosed() | |
// Mock an error | |
mock.ExpectQuery(mockQueryFindShipper).WithArgs(124). | |
WillReturnError(sql.ErrNoRows). | |
RowsWillBeClosed() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't really get you @c9s? I saw nothing like that in my side.