DEV Community

Discussion on: Using mock on Golang tests

Collapse
 
dineshkushwaha profile image
Dinesh Kushwaha

We have not made any database connection here. db.open. Do we need that or mock will do for us.
We need to add the connection_string to interact with db

Collapse
 
rafaacioly profile image
Rafael Acioly

That's the point Dinesh, this post show how to mock the database connection so your tests don't depend of a external software to run consequently running faster, there is no need to create a "connection_string" because the real connection never happens.

Collapse
 
dineshkushwaha profile image
Dinesh Kushwaha • Edited

I am writing mock test for the first time, how it will show us the correct result if it is not connecting to the db. Can you provide me one complete example where I can run the test and check. In my case, I have a select query and I want to do the mock test. I have used gorm for the connection.
If you want I can share the code with you

Here is the mock code which I am trying but facing issue :

product_test.go
func TestFindPublication(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
myDb := mock.ExpectQuery("SELECT * FROM product_data").
// the number 3 must be on the query like "where id = 3"
WithArgs("ST")
myDB := repo.NewProductRepository()
result,err := myDB.FindProductFromPublication("ST")
if err != nil {
t.Errorf("something went wrong: %s", err.Error())
}
assert.Equal(t, myDb,result)
}

product.go :

// ProductRepository Interface implemented
type ProductRepository interface {
FindProductFromPublication(pub string) ([]model.Product, error)
}

// ProductRepositoryImpl repository to product table
type ProductRepositoryImpl struct {
conn *gorm.DB
}

// NewProductRepository construct product repository
func NewProductRepository() ProductRepository {
return ProductRepositoryImpl{}
}

// FindProductFromPublication based on pub
func (productListRepository ProductRepositoryImpl) FindProductFromPublication(pub string) ([]model.Product, error) {
err := productListRepository.connect()
if err != nil {
return nil, err
}
var products []model.Product
err = productListRepository.conn.Where("publication_id = ?", pub).Find(&products).Error
defer productListRepository.close()
return products, err
}

func (productListRepository *ProductRepositoryImpl) connect() error {
conn, err := database.Connect()
if err != nil {
return err
}
productListRepository.conn = conn
return nil
}

func (productListRepository ProductRepositoryImpl) close() {
err := productListRepository.conn.Close()
if err != nil {
log.Fatalf("unable to close the database %s", err)
}

}