所以我想在测试中将控制器与模型隔离,这样我就可以在出现问题时轻松解决问题。之前,我只是使用模拟数据访问端点,但很难排除故障,因为测试从路由器一直运行到数据存储。所以我想也许我会为每个控制器(和模型)创建两个版本(MockController vs Controller),并根据模式变量的值使用一个。简而言之,这就是我计划实施它的方式。
const mode string = "test"
// UserModelInterface is the Interface for UserModel
type UserModelInterface interface {
Get()
}
// UserControllerInterface is the Interface for UserController
type UserControllerInterface interface {
Login()
}
// NewUserModel returns a new instance of user model
func NewUserModel() UserModelInterface {
if mode == "test" {
return &MockUserModel{}
} else {
return &UserModel{}
}
}
// NewUserController returns a new instance of user controller
func 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(),只验证有效负载并返回有效响应。
你觉得这个设计怎么样?你有更好的实现吗?
慕码人2483693
慕沐林林
相关分类