Testify, mock unexpected method call when the expectation is already written , but the method is called twice with different parameter

Viewed 272

I have an use case method that call a mocked repository method two times with a different parameter

I've written it somewhat like this

func TestInitUserSubscription(t *testing.T) {
    aRepository := &aRepositoryMock{}

    //this expected method is called twice
    aRepository.On("GetByID", data.ID).Return(*data, nil)

    bUseCase := New(
        aRepository,
    )

    result, err := bUseCase.Init(data.Name)
}

running the test, results in these following error

mock: Unexpected Method Call
-----------------------------

GetByID(uint64)
                0: 0x0

The closest call I have is:

GetByID(uint64)
                0: 0x1


Diff: 0: FAIL:  (uint64=0) != (uint64=1) [recovered]
        panic:

mock: Unexpected Method Call
-----------------------------

GetByID(uint64)
                0: 0x0

The closest call I have is:

GetByID(uint64)
                0: 0x1


Diff: 0: FAIL:  (uint64=0) != (uint64=1)

I'm assuming this is because the the method is called with different parameter, I've tried to use .Twice() but didn't solve the problem

Helps would be very much appreciated

2 Answers

You should add two expectations with different values:

   //this expected method is called twice
    aRepository.On("GetByID", 0).Return(*data, nil)
    aRepository.On("GetByID", 1).Return(*anotherData, nil)

I guess you will want to return a different value depending on the ID given as parameter.

mock: Unexpected Method Call
-----------------------------

GetByID(uint64)
                0: 0x0

The closest call I have is:

GetByID(uint64)
                0: 0x1

This message means that test expects ID = 1, but it received 0.

Check your code and tests arrangements to pass 1 into GetByID() method when you are running test.

Related