Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

calling Recorder methods with numbers causes misses due to Go's untyped constant rules #16

@jmhodges

Description

@jmhodges

With an interface

type Adder interface{
   Inc(x int64) error
 }

the code generated for the MockAdder has the correct int type:

 func (_m *MockAdder) Do(_param0 int64) error {

while the Recorder has interface{}s for the argument:

func (_m *MockAdderRecoder) Do(arg0 interface{}) error {

This, unfortunately, causes spurious missed expectation in the test case below. This is because the "2" is handed to the AdderRecorder as an int. This is Go's untyped int handling code choosing int instead of int64 as its default type since none is provided explicitly.

It looks plausible from the code to generate the Recorder methods with the right argument types and convert them down as the call method one does. (But maybe I haven't seen the bug that prevented that in the first place.)

One workaround is to just use the same variable in both places and another is to explicitly convert it to the right type, but it might nice for small tests to just make the right type.

type Thing struct { a Adder }
func (t Thing) CallsAdderInc(x int64) { t.a.Inc(x) }

func TestAdder(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()
    adder := NewMockAdder(ctrl)
    myThing := Thing{adder}
    adder.EXPECT().Inc(2).Return(nil) // This 2 is turned into int instead of int64
    myThing.CallsAdderInc(2)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions