假設我在 golang 中有以下界面
type InterfaceA interface {
Method1()
Method2()
}
func (o *Obj) Method1() {
o.Method2()
}
func (o *Obj) Method2() {
}
obj1 := //instantiate a type that implements the above interface
如果我正在為 撰寫單元測驗Method1,我如何創建一個模擬物件,Obj同時在Method1真實Obj物件上執行代碼?我們面臨的挑戰是,Obj呼叫Method2它有可能成為嘲笑物件,而Method1真正的物件上呼叫的需求。
uj5u.com熱心網友回復:
Go 并沒有真正的動態調度。Method1()接收器的型別o是*Obj這樣的,運算式o.Method2()將始終呼叫Obj.Method2(),這里根本不涉及介面。
所以你想要的是不可能的。但這應該不是問題,因為我們通常在物件級別而不是方法級別進行單元測驗。
uj5u.com熱心網友回復:
我不確定,如果我明白你為什么要這樣做。但是您可以將“真實”物件添加為模擬物件的欄位并呼叫其方法。
// the mock object has a field of type Obj
type MockObject struct {
obj Obj
}
// then it can call the "real" objects method
func (o *MockObject) Method1() {
o.obj.Method2()
}
func (o *MockObject) Method2() {
}
我有時會做這樣的事情來實作一個介面。例如,如下所示。這樣我就可以使用服務器型別并將其粘貼進去,ListenAndServe因為它實作了ServeHTTP.
type Server struct {
router *http.ServeMux
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func NewServer() *Server {
return &Server{
router: http.NewServeMux(),
}
}
s := NewServer()
http.ListenAndServe(":8080", s)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389703.html
