why my localhost don't send any data when using database interface for mocking in Golang unit test?

Viewed 30

I'm new in golang. I want to write unit tests for my functions that save data in mongodb, that are a little complicated. There are many nested functions. e.g. A calls B, inside B, C and D is called, finally D calls E function that has a database query like Find. I followed the instructions of RESTful API in Golang using Echo - MongoDB Unit Testing in Golang in youtube.

So I decided to start from a little function like E. Here is the little function that I tried to mock database relation for it:

func LoadUserRoles(username interface{}) ([]UserRoles, error) {

    q := bson.M{"username": username}
    ps := new([]UserRoles)
    if err := userRoleDB.Find(q).All(ps); err != nil {
        return nil, err
    }
    
    return *ps, nil
}

I created an interface that implements exactly the Find method of mgo driver. the interface is like:

type CollectionAPI interface {
    Find(query interface{}) *mgo.Query
}

Then I created an instance of this interface and took instead of userRoleDB:

var userRoleMockDB      dbinterface.CollectionAPI

So my LoadUserRoles function changed to:

func LoadUserRoles(username interface{}) ([]UserRoles, error) {
    q := bson.M{"username": username}

    ps := new([]UserRoles)

    if err := userRoleMockDB.Find(q).All(ps); err != nil {
        return nil, err
    }
    return *ps, nil
}

The result is error in connecting to db.

Exact error:

localhost didn’t send any data.

ERR_EMPTY_RESPONSE

0 Answers
Related