当前位置: > > > > 测试返回接口的函数
测试返回接口的函数
来源:stackoverflow
2024-04-19 11:09:34
0浏览
收藏
学习知识要善于思考,思考,再思考!今天米云小编就给大家带来《测试返回接口的函数》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!
问题内容
我在为下面的案例编写测试时遇到困难。
我可以使用仅实现我自己使用的功能的模拟对象编写“helper”测试。
如何使用模拟对象为函数“new”编写测试代码而不模拟函数 c()、d()?
可能是另一个包写得不好,它不应该返回接口而是实际的结构?
package main
import (
"fmt"
)
func main() {
New()
}
func New() {
new(NewFromEnvironment)
}
type newTopology func()(Interface,error)
// new is non-exposed simply used for testing purpose.
func new(newTopology newTopology) {
t,_ := newTopology()
helper(t)
}
// I need to call only A and B
type topologyInterface interface {
A() string
B() string
}
func helper(topology topologyInterface) {
s1 := topology.A()
s2 := topology.B()
fmt.Println(s1 + "," + s2)
}
// Below are from other package named "topology".
// I have no control to the code below.
type Interface interface {
A() string
B() string
C() string
D() string
//... more
}
func NewFromEnvironment() (Interface, error) {
return P{}, nil
}
type P struct{}
func (p P) A() string {
return "A"
}
func (p P) B() string {
return "B"
}
func (p P) C() string {
return "C"
}
func (p P) D() string {
return "D"
}
// more...
解决方案
您可以尝试创建一个嵌入 p 的结构 mockp。然后 mockp 继承 p 的所有方法,但您可以使用自己的模拟实现来隐藏 a() 和 b() 。这是一个例子:
package main
import (
"fmt"
)
type interface interface {
a()
b()
}
type p struct {
}
func (p p) a() {
fmt.println("a")
}
func (p p) b() {
fmt.println("b")
}
type mockp struct {
p
}
// shadow p's b() method
func (p mockp) b() {
fmt.println("mock b")
}
func main() {
var p interface = mockp{}
p.a()
p.b()
}
输出:
A Mock B
本篇关于《测试返回接口的函数》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注米云公众号!
