I'm working on my first Go + Gin + GORM project. I've two models: List
and Todo
as follows:
type List struct {
gorm.Model
Name string
Todos []*Todo `gorm:"many2many:list_todos;"`
}
type Todo struct {
gorm.Model
Title string
Lists []*List `gorm:"many2many:list_todos;"`
}
I've a helper function to add a Todo
to a List
:
func (self *List) AddTodos(db *gorm.DB, todos ...*Todo) error {
return db.Model(self).Association("Todos").Append(todos)
}
I want to unit test the AddTodos
function. I'm using sqlmock
for mocking. This is the code for the unit test:
func TestAddTodosWithNoTodos(t *testing.T) {
gormDB, db, mock, _ := misc.GetMockedGormDBWithMock()
defer db.Close()
mockList := &List{
Model: gorm.Model{ID: 1},
}
mock.NewRows([]string{"id"}).AddRow(mockList.ID)
if err := mockList.AddTodos(gormDB); err != nil {
// test fails here
t.Errorf("Expected no error, got %v", err)
}
todos := []Todo{}
if err := gormDB.Model(mockList).Association("Todos").Find(&todos); err != nil {
// test also fails here
t.Errorf("Expected no error, got %v", err)
}
if len(todos) != 0 {
t.Errorf("Expected no todos, got %v", todos)
}
}
I've marked the two places where the test fails. The error
object being checked at both these places are from GORM, however, in the test failure error messages, it is revealed that sqlmock
is causing these errors:
First error message:
Expected no error, got all expectations were already fulfilled, call to database transaction Begin was not expected
Second error message:
Expected no error, got all expectations were already fulfilled
I don't want to test which queries are executed, hence, I've not used sqlmock
's ExpectQuery
. Still, "unexpected queries" are causing errors.
How can I unit test AddTodos
without testing the queries it performs?