亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何測試依賴是否被正確調用

如何測試依賴是否被正確調用

Go
料青山看我應如是 2023-05-15 14:53:23
在 Go 中,我將如何測試是否以正確的方式調用了模擬依賴項。如果我有一個接受依賴接口的結構,注入后我希望能夠測試原始模擬對象是否已被調用。我在這個例子中的當前代碼我看不到結構值已經改變。如果我更改我的代碼以通過引用傳遞它會觸發錯誤:s.simpleInterface.Call 未定義(類型 *SimpleInterface 是指向接口的指針,而不是接口)type SimpleInterface interface {    Call()}type Simple struct {    simpleInterface SimpleInterface}func (s Simple) CallInterface() {    s.simpleInterface.Call()}type MockSimple struct {    hasBeenCalled bool}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")    }}
查看完整描述

1 回答

?
慕虎7371278

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")

    }

}


查看完整回答
反對 回復 2023-05-15
  • 1 回答
  • 0 關注
  • 178 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號