服务对象可以具有这样的接口
type Service struct { serviceK typeK serviceHttp serviceHttp // of type interface hence can be mocked}普通应用程序代码可以使用实际对象初始化服务。测试将包含模拟对象
type Req struct {}type Resp struct {}type ServiceHttp interface{ HttpReq(params Req)(Resp, error)}type Implementation struct {}func (i *Implementation)HttpReq(params Req)(Resp, error){ // buid http request}func (c *Service) invoke(Connection Connection, args []string) { service, err := c.getService(Connection, args) serviceC, err := c.getServiceK(service, []string{"url", “user”, “id”}) c := strings.Fields(serviceC) serviceImp := c.GetServiceImp() // init params with the required fields val, err := c.HttpReq(params) if err != nil { fmt.println(err) } fmt.Print(string(val))}运行测试时,可以使用模拟实现初始化服务对象,该实现返回虚拟响应。
type MockImplementation struct {}func (i *MockImplementation)HttpReq(Resp, error){ // return mock response}func TestMain(){ services := { serviceHttp:MockImplementation{}, serviceK: typeK{}, // initialise this }}这是测试它的方法之一。其他方法可能是我猜httpReq返回http.ResponseWriter的地方,您可以使用httptest.ResponseRecorder对其进行测试。



