我在為下面的案例編寫測試時遇到了困難。我能夠使用僅實現我自己使用的功能的模擬對象為“助手”編寫測試。如何使用不模擬函數 C()、D() 的模擬對象為函數“new”編寫測試代碼?可能是另一個包寫得不好,它不應該返回一個接口,而是返回實際的結構?package mainimport ( "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 Btype 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...
1 回答

holdtom
TA貢獻1805條經驗 獲得超10個贊
您可以嘗試創建一個MockP嵌入P. ThenMockP繼承了 的所有方法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
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消