1 回答

TA貢獻1802條經驗 獲得超4個贊
我看到三種簡單的方法來解決這個問題:
1- 更改 Call 方法的簽名以接收指向 MockSimple 的指針,并在實例化 Simple 結構時,為其提供 mock 的地址:
func (ms *MockSimple) Call() {
ms.hasBeenCalled = true
}
func TestMockCalled(t *testing.T) {
ms := MockSimple{}
s := Simple{
simpleInterface: &ms,
}
s.CallInterface()
if ms.hasBeenCalled != true {
t.Error("Interface has not been called")
}
}
2-不是最干凈的解決方案,但仍然有效。如果您真的不能使用#1,請使用它。在其他地方聲明“hasBeenCalled”并更改您的 MockSimple 以保存指向它的指針:
type MockSimple struct {
hasBeenCalled *bool
}
func (ms MockSimple) Call() {
*ms.hasBeenCalled = true
}
func TestMockCalled(t *testing.T) {
hasBeenCalled := false
ms := MockSimple{&hasBeenCalled}
s := Simple{
simpleInterface: ms,
}
s.CallInterface()
if hasBeenCalled != true {
t.Error("Interface has not been called")
}
}
3- 可能是一個非常糟糕的解決方案:使用全局變量,所以我只會將其用作最后的手段(始終避免全局狀態)。使“hasBeenCalled”成為全局變量并從方法中對其進行修改。
var hasBeenCalled bool
type MockSimple struct{}
func (ms MockSimple) Call() {
hasBeenCalled = true
}
func TestMockCalled(t *testing.T) {
ms := MockSimple{}
s := Simple{
simpleInterface: ms,
}
s.CallInterface()
if hasBeenCalled != true {
t.Error("Interface has not been called")
}
}
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報