英文:
Testify, mock unexpected method call when the expectation is already written , but the method is called twice with different parameter
问题
我有一个使用案例方法,调用了一个模拟的存储库方法两次,参数不同。
我写的代码大致如下:
func TestInitUserSubscription(t *testing.T) {
aRepository := &aRepositoryMock{}
// 这个期望的方法被调用了两次
aRepository.On("GetByID", data.ID).Return(*data, nil)
bUseCase := New(
aRepository,
)
result, err := bUseCase.Init(data.Name)
}
运行测试时,出现以下错误:
mock: 意外的方法调用
-----------------------------
GetByID(uint64)
0: 0x0
最接近的调用是:
GetByID(uint64)
0: 0x1
Diff: 0: FAIL: (uint64=0) != (uint64=1) [recovered]
panic:
mock: 意外的方法调用
-----------------------------
GetByID(uint64)
0: 0x0
最接近的调用是:
GetByID(uint64)
0: 0x1
Diff: 0: FAIL: (uint64=0) != (uint64=1)
我猜测这是因为该方法被使用了不同的参数调用。我尝试使用.Twice()
,但问题没有解决。
非常感谢您的帮助。
英文:
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
答案1
得分: 1
你应该添加两个具有不同值的期望:
//这个期望方法被调用两次
aRepository.On("GetByID", 0).Return(*data, nil)
aRepository.On("GetByID", 1).Return(*anotherData, nil)
我猜你想根据给定的ID参数返回不同的值。
英文:
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.
答案2
得分: -1
这条消息意味着测试期望的ID是1,但实际接收到的是0。
请检查你的代码和测试安排,在运行测试时将1传递给GetByID()
方法。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论