testify icon indicating copy to clipboard operation
testify copied to clipboard

Mock to skip comparing dates?

Open ricardolonga opened this issue 7 years ago • 4 comments

Is there any way for mock to skip comparing dates? There is a difference in the milliseconds.

ricardolonga avatar Nov 29 '16 12:11 ricardolonga

@ricardolonga sorry for the late reply, I've been traveling a lot the past few months.

Is the problem with using something like On("SomeMethod", time.Now())?

Would mock.MatchedBy or mock.AnythingOfType work?

ernesto-jimenez avatar Dec 17 '16 19:12 ernesto-jimenez

i have a similar requirement. I tried using AnythingOfType, does it work for custom types(pointer to struct ) as well or just golang types ?. I couldnt make it work It would be nice to say compare everything except a fields starting with name "time*" :-)

krmayankk avatar Feb 24 '17 08:02 krmayankk

I have similar requirement too.

soosai-cs avatar Jan 06 '22 07:01 soosai-cs

I'd be hesitant about adding something as specific as an option to ignore fields in structs beginning with substrings when doing argument matching, there are so many possibilities. Custom matching like this is exactly what mock.MatchedBy is for, and it does work for the time example, here is code for "within 2 milliseconds":

package kata

import (
	"testing"
	"time"

	"github.com/stretchr/testify/mock"
)

type MyStruct struct {
	msg  string
	time time.Time
}

type MyMock struct {
	mock.Mock
}

func (m *MyMock) Do(st MyStruct) {
	m.Called(st)
}

func TestTestify(t *testing.T) {
	m := &MyMock{}
	m.Test(t)
	defer m.AssertExpectations(t)
	testTime := time.Now()
	m.On("Do", mock.MatchedBy(func(st MyStruct) bool {
		return st.msg == "hello" &&
			st.time.Sub(testTime) < 2*time.Millisecond &&
			st.time.Sub(testTime) > -2*time.Millisecond
	})).Return().Once()
	time.Sleep(time.Millisecond)
	s := MyStruct{
		msg:  "hello",
		time: time.Now(),
	}
	m.Do(s)
}

You need to be careful about where you call time.Now(), the function in mock.MachedBy is run after the call to m.Do(), not during the call to m.On().

brackendawson avatar Jan 06 '22 14:01 brackendawson