gpt4 book ai didi

unit-testing - 我可以使用嵌套界面模拟库代码吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:33 24 4
gpt4 key购买 nike

<分区>

我正在尝试在我的 go 代码中的测试中模拟第 3 方库。但是我无法编译我所采用的方法。如果我想模拟 T2.M2 的结果,有什么方法可以使它工作,或者我可以采用另一种方法吗?

package main

import (
"fmt"
)

// Two types in a library that I dont have control over
type T1 struct {}
func (T1) M1() T2 {
return T2{}
}
type T2 struct {}
func (T2) M2() {
fmt.Println("hello world")
}

// I created these interfaces in order to assign an instance of T1
// to a variable of type I1 so that I can mock the behavior of T2.M2()
// problem is that this doesn't compile.
type I1 interface {
M1() I2
}
type I2 interface {
M2() // I want to mock this method
}

// Then I would be able to create a mock
type Mock1 struct {}
func (Mock1) M1() I2 {
return Mock2{}
}
type Mock2 struct {}
func (Mock2) M2() {
fmt.Println("HELLO WORLD")
}

func main() {
var i1 I1
i1 = T1{}
i1.M1().M2()
i1 = Mock1{}
i1.M1().M2()
}

https://play.golang.org/p/sv-Uuuke1dr

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