gpt4 book ai didi

go - 如何测试依赖是否被正确调用

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

在 Go 中,我将如何测试是否以正确的方式调用了模拟依赖项。

如果我有一个接受依赖项接口(interface)的结构,注入(inject)后我希望能够测试原始模拟对象是否已被调用。

我在这个例子中的当前代码我看不到结构值已经改变。如果我更改我的代码以通过引用传递它会触发错误:

s.simpleInterface.Call 未定义(类型 *SimpleInterface 是指向接口(interface)的指针,而不是接口(interface))

type SimpleInterface interface {
Call()
}

type Simple struct {
simpleInterface SimpleInterface
}

func (s Simple) CallInterface() {
s.simpleInterface.Call()
}

type MockSimple struct {
hasBeenCalled bool
}

func (ms MockSimple) Call() {
ms.hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
ms := MockSimple{}
s := Simple{
simpleInterface: ms,
}
s.CallInterface()

if ms.hasBeenCalled != true {
t.Error("Interface has not been called")
}
}

最佳答案

我看到三个简单的方法来解决这个问题:

1- 更改 Call 方法的签名以接收指向 MockSimple 的指针,并在实例化 Simple 结构时为其提供模拟地址:

func (ms *MockSimple) Call() {
ms.hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
ms := MockSimple{}
s := Simple{
simpleInterface: &ms,
}
s.CallInterface()

if ms.hasBeenCalled != true {
t.Error("Interface has not been called")
}
}

2- 不是最干净的解决方案,但仍然有效。如果您真的不能使用#1,请使用它。在其他地方声明“hasBeenCalled”并更改您的 MockSimple 以保存指向它的指针:

type MockSimple struct {
hasBeenCalled *bool
}

func (ms MockSimple) Call() {
*ms.hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
hasBeenCalled := false
ms := MockSimple{&hasBeenCalled}
s := Simple{
simpleInterface: ms,
}
s.CallInterface()

if hasBeenCalled != true {
t.Error("Interface has not been called")
}
}

3- 可能是一个非常糟糕的解决方案:使用全局变量,所以我只会将其用作最后的手段(始终避免全局状态)。使“hasBeenCalled”成为全局变量并从方法中对其进行修改。

var hasBeenCalled bool

type MockSimple struct{}

func (ms MockSimple) Call() {
hasBeenCalled = true
}

func TestMockCalled(t *testing.T) {
ms := MockSimple{}
s := Simple{
simpleInterface: ms,
}
s.CallInterface()

if hasBeenCalled != true {
t.Error("Interface has not been called")
}
}

干杯!

关于go - 如何测试依赖是否被正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687449/

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