testify
testify copied to clipboard
Mock to skip comparing dates?
Is there any way for mock to skip comparing dates? There is a difference in the milliseconds.
@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?
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*" :-)
I have similar requirement too.
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()
.