gpt4 book ai didi

go - 测试函数是否被调用

转载 作者:IT王子 更新时间:2023-10-29 02:00:51 30 4
gpt4 key购买 nike

给定这个结构和函数:

type ExampleModule struct {
DB *database.Store
AnotherModule AnotherModuleInterface
}

func(m *ExampleModule) A (i int, id int[]) error{
err := m.AnotherModuke.SomeFunc(i, id)
}

如何进行单元测试以确保在运行函数 A 时调用 SomeFunc

最佳答案

  1. 你可以模拟接口(interface)的实现,比如
globalIndex
type Mock struct{}

func (m Mock) SomeFunc(){
globalIndex++
}

func testA(t *testing.T) {
a := ExampleModule{
AnotherModule: Mock{},
}
a.A()
assert(globalIndex == 1)
}

  1. 尝试作证AssertExpectations 可以帮到你

https://github.com/stretchr/testify#mock-package

关于go - 测试函数是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252807/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com