你如何在 GoLang 的模拟中模拟错误返回值?
Posted
技术标签:
【中文标题】你如何在 GoLang 的模拟中模拟错误返回值?【英文标题】:How do you mock an error return value in mockery for GoLang? 【发布时间】:2020-02-20 22:40:46 【问题描述】:我正在使用https://github.com/vektra/mockery 来生成我的模拟文件。
假设我对函数 GetQualifyingListOfBooks
进行了此测试。 (模拟的)客户端方法GetListOfBooks
的签名是:
func GetListOfBooks(ctx context.Context, in *GetListOfBooksRequest, opts ...grpc.CallOption) (*GetListOfBooksResponse, error)
目标:我想模拟GetListOfBooks
返回错误的情况,所以我写了如下:
package whatever
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
mock "github.com/stretchr/testify/mock"
mockClients "github.com/MyOrg/MyApp/internal/app/myservice/mocks"
)
func TestGetQualifyingListOfBooks (t *testing.T)
client := &mockClients.BookClient
client.On("GetListOfBooks", mock.Anything, mock.Anything).Return(nil, mock.AnythingOfType("error"))
realInstance.bookClient = client
b, err := GetQualifyingListOfBooks(realInstance, 10) // this calls `GetListOfBooks`
assert.Nil(t, b)
assert.NotNil(t, err)
但它对此感到恐慌:
--- FAIL: TestGetQualifyingListOfBooks (0.00s)
panic: assert: arguments: Error(1) failed because object wasn't correct type: Error(1) [recovered]
panic: assert: arguments: Error(1) failed because object wasn't correct type: Error(1)
如何模拟错误的返回值?
【问题讨论】:
【参考方案1】:改变这一行
client.On("GetListOfBooks", mock.Anything, mock.Anything).Return(nil, mock.AnythingOfType("error"))
到这里
client.On("GetListOfBooks", mock.Anything, mock.Anything).Return(nil, errors.New("hello world"))
为我做的。
【讨论】:
似乎很单调以上是关于你如何在 GoLang 的模拟中模拟错误返回值?的主要内容,如果未能解决你的问题,请参考以下文章