How to assert param type of `gomock.Expect` call

107 Views Asked by At

I am using gomock for my unit test. I need to assert the type of param passed in the EXPECT setup. For example below, I need to assert the first param is any of type String, then any of type Integer, and then any of type MyStruct.

mockFoo.EXPECT().MyFunc(gomock.Any(), gomock.Any(), gomock.Any()).Return(true)

In Java, I'd do something like this:

Foo mockFoo = mock(Foo.class);
when(mockFoo.myFunc(anyString(), anyInt(), any(MyStruct.class))).thenReturn(true);

I couldn't find anything in the documentation.

1

There are 1 best solutions below

4
kozmo On

Implements a custom Matcher for required args. For example:

type Foo interface {
    MyFunc(string) bool
}

type matcher struct {
    // implements any required fields.
}

func (n matcher) Matches(in any) bool {
    val, ok := in.(string)
    fmt.Printf("value [%v], ok [%v]\n", val, ok) // gets access to the arg
    return ok
}

func (n matcher) String() string {
    return "not match"
}
mockFoo.EXPECT().MyFunc(matcher{}).Return(true)

PLAYGROUND

☝ It's the simplest example.

For mote flexibility implement a custom Matcher with any required logic. Also try to use generics, for example:

type Foo interface {
    MyFunc(string, int) bool
}
type matcher[T any] struct {
    // implements any required fields. `matchFn` using only for example
    matchFn func(in T) bool
}

func (n *matcher[T]) Matches(in any) bool {
    val, ok := in.(T)
    if !ok {
        return false
    }
    return n.matchFn(val)
}

func (n *matcher[T]) String() string {
    return "some msg"
}
type matcherPerType[T any] struct {
    // implements any required fields.
    match T
}

func (n *matcherPerType[T]) Matches(in any) bool {
    val, ok := in.(T)
    if !ok {
        return false
    }
    // `reflect.DeepEqual` using only for example
    return reflect.DeepEqual(val, n.match)
}

func (n *matcherPerType[T]) String() string {
    return "some msg"
}
mockFoo.EXPECT().MyFunc(
    &matcher[string]{matchFn: func(in string) bool {
        return strings.EqualFold(in, "some_string")
    }},
    &matcherPerType[int]{match: 1},
).Return(true)

PLAYGROUND