卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章70042本站已运行4223

golang框架的可测试代码依赖管理技巧

在 go 框架中管理可测试代码依赖项的方法包括:使用 mocking 包模拟真实依赖项,检查模拟对象是否按预期调用;使用 stubbing 在真实依赖项的函数上创建桩函数,模拟简单操作;使用依赖注入允许在运行时动态注入依赖项,简化测试。

golang框架的可测试代码依赖管理技巧

Go 框架可测试代码依赖管理的技巧

在 Go 框架中编写可测试代码至关重要,因为它使我们能够轻松地隔离和测试我们代码的不同部分。然而,管理测试代码的依赖项可能是一项挑战,尤其是在使用较大的框架和第三方库时。

使用 Mocking 包

使用 Mocking 包(例如 github.com/stretchr/testify/mock)可以模拟测试代码中真实的依赖项。这允许我们根据提供的输入检查模拟对象是否被正确调用,从而隔离特定区域进行测试。

import (
    "testing"

    "github.com/stretchr/testify/mock"

    "my/package"
)

type MyInterface mock.Mock

func (m *MyInterface) MyMethod(input string) string

func TestMyFunction(t *testing.T) {
    mockedInterface := new(MyInterface)
    mockedInterface.On("MyMethod", "foo").Return("bar")

    actual := package.MyFunction(mockedInterface, "foo")
    expected := "bar"

    if actual != expected {
        t.Errorf("Expected %s, got %s", expected, actual)
    }
}

使用 Stubbing

Stubbing 类似于 Mocking,但它直接在真实依赖项的函数上创建桩函数。这用于模拟简单的操作,例如数据库查询或 HTTP 调用。

立即学习“go语言免费学习笔记(深入)”;

import (
    "testing"

    "my/package"
)

func TestMyFunction(t *testing.T) {
    package.StubMyMethod = func(input string) string {
        return "stubbed output"
    }

    actual := package.MyFunction("foo")
    expected := "stubbed output"

    if actual != expected {
        t.Errorf("Expected %s, got %s", expected, actual)
    }
}

依赖注入

依赖注入是一种设计模式,允许我们在运行时动态注入依赖项。这允许我们在测试期间轻松地替换真实依赖项的 Mock 或 Stub,从而简化测试过程。

import (
    "testing"

    "my/package"
)

func TestMyFunction(t *testing.T) {
    type MyInterface interface {
        MyMethod(input string) string
    }

    f := func(i MyInterface) string {
        return i.MyMethod("foo")
    }

    mockedInterface := new(MyInterface)
    mockedInterface.On("MyMethod", "foo").Return("bar")

    actual := f(mockedInterface)
    expected := "bar"

    if actual != expected {
        t.Errorf("Expected %s, got %s", expected, actual)
    }
}

实战案例

以一个文件上传服务为例。该服务使用第三方库来处理文件上传。我们可以使用 Mocking 来测试该服务的上传功能,而不依赖于实际的文件上传。

import (
    "context"
    "io"
    "testing"

    "github.com/stretchr/testify/mock"

    "my/package"
)

type FileUploader mock.Mock

func (m *FileUploader) Upload(ctx context.Context, r io.Reader, fileName string) (string, error)

func TestUploadFile(t *testing.T) {
    mockedUploader := new(FileUploader)
    mockedUploader.On("Upload", mock.Anything, mock.Anything, mock.Anything).Return("stubbed-file-id", nil)

    service := mypackage.NewService(mockedUploader)

    id, err := service.UploadFile(context.Background(), nil, "file.txt")

    if err != nil {
        t.Errorf("Expected no error, got: %s", err)
    }

    if id != "stubbed-file-id" {
        t.Errorf("Expected stubbed file id, got: %s", id)
    }
}

结论

管理 Go 框架中可测试代码的依赖项对于确保可靠和可维护的代码非常重要。通过利用 Mocking、Stubbing 和依赖注入等技术,我们可以有效地隔离和测试不同组件,从而提升测试覆盖率和代码质量。

卓越飞翔博客
上一篇: C++框架在物联网设备中的使用
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏