讓我們看一下這個例子:
套餐一:
type Client struct {
log bool
client *http.Client
}
type Report struct {
cli *Client
}
包 B:
type H struct {
r *A.Report
...............
}
現在我想在包 B 中撰寫一個測驗用例,它需要來自包 A 的模擬報告。包 B 使用包 A 報告來執行函式呼叫。
例如:
H.r.functionA()
本質上,我需要為上面的示例制作一個模擬函式。但是如何為包 B 創建一個模擬報告,以便我可以在包 A 測驗檔案中使用它?
uj5u.com熱心網友回復:
首先,如果要撰寫模擬,則需要介面。你不能用結構來做到這一點。在上面的示例中,您使用的是結構。這是從functionA()實作Report介面的型別上獲得模擬回應所需的內容。在包 B 中,您應該定義一個介面
type Report interface {
functionA()
}
現在你有了一個介面,你需要改變你的型別H來保存這個介面,而不是你在包 A 中定義的結構。
type H struct {
r Report
...............
}
現在您可以提供介面的模擬實作Report
type mockReport struct {
}
func (m *mockReport) functionA() {
// mock implementation here
}
在您創建型別實體時的測驗檔案中H,只需為其提供mockReport實體
h := H{r: &mockReport{}}
h.r.functionA() // this will call the mocked implementation of your
//function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444028.html
上一篇:在2個goroutine之間同步
