简体   繁体   中英

how to mock database layer in golang using testify/mock

I am trying to run unit test on a server, and using "github.com/stretchr/testify/mock" for mocking database layer. Putting all the code here will make it very messy so i created a small project which will give the idea of my code structure and what i am really trying to achieve " https://github.com/utkarsh17ife/goMockPractice ". You can pull this code and run "go test ./..." (Not sure giving the github link is the correct thing to do here, but i feel it will make things easier)

Server struct has a field db which is of type interface, so when we create a normal server the db is assigned with the real database, but while testing it is assigned with the mock database. But the problem is i cannot do the below on the db

srv.db.On("Insert", "some data").Return(true)
srv.db.AssertExpectations(t)

As the db interface does not have "On" and "AssertExpectations" field.

Looks like this is not the way to implement mocking, please let me know correct way of testing this.

You can add whatever functions you want to your mock struct. The only limitation is that it has to implement at least the DbStore interface. Any additional functions are fine to add if you need them for your tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM