我如何模擬在包init()方法中調用的東西?例如:主程序var myService MyService = myservicepkg.New()func init(){ response := myService.get()}func otherMethod(){ //do something}主測試.gofunc Test_otherMethod(){ ctrl := NewController(t) defer ctrl.Finish() myServiceMock = myservicepkg.NewMock(myService) myServiceMock.EXPECT().get().return("success")}問題是init()在服務被模擬替換之前被調用。
3 回答
烙印99
TA貢獻1829條經驗 獲得超13個贊
這是使用可變全局狀態的問題。
我的建議是添加一個標志以在某些條件下不運行它,或者公開一個可以在內部測試中恢復/更新這個全局變量的私有函數。
這反映了您的設計:如果測試起來很復雜,也許您應該重構。
創建一個帶有字段服務的對象應用程序,在構造函數/構建器/工廠上創建將更容易測試。
init的用法很講究。除了將驅動程序注冊到 sql 包中,我從不使用它(可能是為了處理標志)。
也許你可以在你的設計中添加更多的 OO
RISEBY
TA貢獻1856條經驗 獲得超5個贊
我找到了一個解決方法,您可以阻止初始化代碼在您的測試中執行,并像這樣隔離地測試該方法:
func init(){
if len(os.Args) > 0 && strings.HasSuffix(os.Args[0], ".test") {
log.Printf("skipping jwt.init() for testing")
} else if len(os.Args) > 1 && strings.HasSuffix(os.Args[1], "-test.run") {
log.Printf("skipping jwt.init() for testing")
} else {
response := myService.get()
}
}
這將阻止調用 init 服務調用。
- 3 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消
