package main
import (
"github.com/golang/mock/gomock"
"testing"
)
type Talker interface {
talk() string
}
type Person struct {
moth *Talker
}
func (p *Person) speak() string {
return (*p.moth).talk()
}
func TestPerson(t *testing.T) {
ctrl := gomock.NewController(t)
mockTalker := NewMockTalker(ctl)
person := Person{moth: mockTalker}
}
假設我已經使用 mockgen 為 Talker 界面創建了一個模擬。
我在創建Person{moth: mockTalker}. 我不能通過mockTalker。
uj5u.com熱心網友回復:
不要用戶指標界面。本質上介面是指標
type Person struct {
moth Talker
}
通常,如果函式想要 return interface,它將通過指標回傳新的結構。
import "fmt"
type I interface {
M()
}
type S struct {
}
func (s *S) M() {
fmt.Println("M")
}
func NewI() I {
return &S{}
}
func main() {
i := NewI()
i.M()
}
uj5u.com熱心網友回復:
在您的Person結構中,moth 欄位是*Talker型別。它是一種指標型別的Talker介面。NewMockTalker(ctl)回傳 Talker型別模擬實作。
你可以做兩件事來解決這個問題。
- 將
Person's moth 欄位的型別更改為Talker.
type Person struct {
moth Talker
}
或者
- 將指標參考傳遞
mockTalker給person初始化`
person := Person{moth: &mockTalker}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395328.html
