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

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

如何在測試中將模型與控制器分開?

如何在測試中將模型與控制器分開?

Go
慕森王 2021-08-23 17:51:49
所以我想在測試中將控制器與模型隔離,這樣我就可以在出現問題時輕松解決問題。之前,我只是使用模擬數據訪問端點,但很難排除故障,因為測試從路由器一直運行到數據存儲。所以我想也許我會為每個控制器(和模型)創建兩個版本(MockController vs Controller),并根據模式變量的值使用一個。簡而言之,這就是我計劃實施它的方式。const mode string = "test"// UserModelInterface is the Interface for UserModeltype UserModelInterface interface {    Get() }// UserControllerInterface is the Interface for UserControllertype UserControllerInterface interface {    Login()}// NewUserModel returns a new instance of user modelfunc NewUserModel() UserModelInterface {    if mode == "test" {        return &MockUserModel{}    } else {        return &UserModel{}    }}// NewUserController returns a new instance of user controllerfunc NewUserController(um UserModelInterface) UserControllerInterface {    if mode == "test" {        return &MockUserController{}    } else {        return &UserController{}    }}type (    UserController struct {um UserModelInterface}    UserModel struct {}    // Mocks    MockUserController struct {um UserModelInterface}    MockUserModel struct {})func (uc *UserController) Login() {}func (um *UserModel) Get() {}func (uc *MockUserController) Login() {}func (um *MockUserModel) Get() {}func main() {    um := NewUserModel()    uc := NewUserController(um)}這樣我就可以跳過 sql 查詢MockUserController.Login(),只驗證有效負載并返回有效響應。你覺得這個設計怎么樣?你有更好的實現嗎?
查看完整描述

2 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

我會讓調用 NewUserController() 和 NewUserModel() 的代碼決定是創建模擬還是真實實現。如果您一直使用這種依賴注入模式直到頂部,您的代碼將變得更清晰,耦合度也會降低。例如,如果用戶控制器被服務器使用,它看起來像這樣:

真實:

u := NewUserController() s := NewServer(u)

在測試中:

u := NewMockUserController() s := NewServer(u)


查看完整回答
反對 回復 2021-08-23
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

我會嘗試一個更纖薄的變體,分布在模型和控制器包上,如下所示:


// inside package controllers


type UserModel interface {

    Get() // the methods you need from the user model

}


type User struct {

    UserModel

}


// inside package models


type User struct {

    // here the User Model

}



// inside package main


import ".....controllers"

import ".....models"


func main() {

    c := &controllers.User{&models.User{}}

}


// inside main_test.go

import ".....controllers"


type MockUser struct {


}



func TestX(t *testing.T) {

    c := &controllers.User{&MockUser{}}

}

對于控制器測試,請考慮httptest 包的ResponseRecorder


查看完整回答
反對 回復 2021-08-23
  • 2 回答
  • 0 關注
  • 208 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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