如何使用Golang从testify/mock中的mock返回mock?

问题描述 投票:0回答:1

是否可以在模拟调用中返回模拟结构?

// Mocks
type mockStorage struct {
    mock.Mock
}

func (m *mockStorage) Bucket(bucket string) *storage.BucketHandle {
    args := m.Called(bucket)
    return args.Get(0).(*storage.BucketHandle)
}

type mockBucketHandle struct {
    mock.Mock
}

func (m *mockBucketHandle) Object(name string) *storage.ObjectHandle {
    args := m.Called(name)
    return args.Get(0).(*storage.ObjectHandle)
}

// Test
func TestStorageClient_LoadChangelog(t *testing.T) {
    // Given
    logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
    zerolog.DefaultContextLogger = &logger
    bucketHandleMock := &mockBucketHandle{}
    bucketHandleMock.On("Object", mock.Anything).Return(&storage.ObjectHandle{})
    storageMock := &mockStorage{}
    storageMock.On("Bucket", mock.Anything).Return(bucketHandleMock)
    client := NewStorageClient(storageMock)

    // When
    handle := client.getObjectHandle(uuid.NewString())
    
    // Then 
    assert.NotNil(t, handle)
}

我正在尝试测试的代码:

func (s *StorageClient) getObjectHandle(url string) *storage.ObjectHandle {
    bucket, name := urlToBucketAndName(url)
    return s.Client.Bucket(bucket).Object(name)
}

这个错误并不完全出乎意料:

panic: interface conversion: interface {} is *sclient.mockBucketHandle, not *storage.BucketHandle [recovered]
unit-testing go mocking testify
1个回答
0
投票

该解决方案需要进行一些重构。本质上,我需要将原始类型包装到我的可模拟类型中。

type googleStorageClient struct {
    client *storage.Client
}

type googleStorageBucketHandle struct {
    handle *storage.BucketHandle
}

type GoogleStorageInterface interface {
    Bucket(name string) GoogleStorageBucketHandleInterface
}

type GoogleStorageBucketHandleInterface interface {
    Object(name string) *storage.ObjectHandle
}

func (g *googleStorageClient) Bucket(name string) GoogleStorageBucketHandleInterface {
    return &googleStorageBucketHandle{handle: g.client.Bucket(name)}
}

func (g *googleStorageBucketHandle) Object(name string) *storage.ObjectHandle {
    return g.handle.Object(name)
}

这允许我使用上面发布的模拟。

© www.soinside.com 2019 - 2024. All rights reserved.