2

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

ggk
  • 117
  • 2
  • 9

2 Answers2

1

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.

davidriod
  • 937
  • 5
  • 14
-1
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.

Dmitry Harnitski
  • 5,838
  • 1
  • 28
  • 43
  • I guess this won't work, the OP has stated that there are going to be 2 different with different values. – davidriod Jul 12 '22 at 03:52