gogomock

is there any way to pass matcher or a workaround to match []interface{} using gomock


for below func InsertManyDocument(data []interface{}) ([]primitive.ObjectID, error)

mock func generated by mockgen is

func (m *MockClient) InsertManyDocument(data []interface{}) ([]primitive.ObjectID, error)
func (mr *MockClientMockRecorder) InsertManyDocument(data []interface{})  *gomock.Call 

now if i wannt to mock the function with MockClient and if data which is coming in acutall function call contains any struct with dynamic values like timestamps(actuall func contains time.now() which willbe added to strct field) how do i pass those while mocking it

and for this function if dynamic values with update howdo i handle validation func (m *MockClient) UpdateOneDocumentWithBSON(filter primitive.D, arrayFilter options.ArrayFilters, update bson.D)

i cant use gomock.any because it returns matcher but the mock func accepts []interface{} and for 2nd example bson.D


Solution

  • In order to test random data like time.Now or Rand, you should make helper interface for them then inject to your service.

    package dthelper
    
    import "time"
    
    type (
        dtHelper struct{}
    
        DTHelper interface {
            Now() time.Time
        }
    )
    
    func NewDTHelper() DTHelper {
        return &dtHelper{}
    }
    
    func (r dtHelper) Now() time.Time {
        return time.Now()
    }
    

    in your testing file, you can mock it like this

    now := time.Now()
    mockDateTimeHelper.EXPECT().Now().Return(now).Times(1)
    

    i cant use gomock.any because it returns matcher but the mock func accepts []interface{} and for 2nd example bson.D

    You could refer DoAndReturn check your params then return value