How to mock objects in Golang 1.19 for testing purposes?

Viewed 30

I'm writing a client built on top of a mongo.Client from the "mongo" package. Because of the nature of mongo client which requires a live database connection, I've decided to try the mocking approach, that is, to store an interface with a set of methods (which also return the interfaces) I would use on the mongo client.

The issue is that the return type of some mongo functions doesn't implement my interfaces for a reason which I do not understand.

For example, mongo.Collection doesn't implement my ICollection interface, however, the mongo.SingleResult does implement the ISingleResult interface:

type ICollection interface {
    FindOne(context.Context, interface{}, ...*options.FindOneOptions) ISingleResult
}

type ISingleResult interface {
    Decode(v interface{}) error
}

The issue is gone if I change the return type from ISingleResult to *mongo.SingleResult, but this is not what I want, because I could not control the *mongo.SingleResult logic and track its calls as I could do with its mock.

Please help me to fix that logic or provide another testing approach which is more common if my is wrong.

0 Answers
Related