首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >与接口的依赖注入有关的问题

与接口的依赖注入有关的问题
EN

Stack Overflow用户
提问于 2016-04-18 15:43:28
回答 1查看 46关注 0票数 0

我有一个包,它提供了一些tcp连接的工作,基本上是这样的:

代码语言:javascript
运行
复制
package connpool

import (
    "io/ioutil"
    "net/http"
)

type ConnPool struct{}

func (pool *ConnPool) GetConn() Conn {
    return Conn{}
}

func (pool *ConnPool) ReleaseConnection(conn Conn)  {

}

type Conn struct{}

func (c Conn) FetchUrl(url string) ([]byte, error) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return []byte{}, err
    }
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    return body, nil
}

然后,我尝试在另一个包中使用它,但通过接口包装它,因为我想在测试环境中用伪连接池替换这个包

代码语言:javascript
运行
复制
package main

import (
    "connpool"
    "fmt"
)

func onlyDependencyOnConnPool() *connpool.ConnPool {
    return &connpool.ConnPool{}
}

type ConnPoolInterface interface {
    GetConn() ConnInterface
    ReleaseConnection(ConnInterface)
}

type ConnInterface interface {
    FetchUrl(string) ([]byte, error)
}

type Fetcher struct{}

func (f Fetcher) Fetch(cPool ConnPoolInterface) error {
    conn := cPool.GetConn()
    defer cPool.ReleaseConnection(conn)
    body, err := conn.FetchUrl("http://localhost:9200")
    fmt.Println("body: ", string(body))
    return err
}

func main() {
    pool := onlyDependencyOnConnPool()
    f := Fetcher{}
    f.Fetch(pool)
}

但它将在编译时返回错误:

代码语言:javascript
运行
复制
./main.go:34: cannot use pool (type *connpool.ConnPool) as type ConnPoolInterface in argument to f.Fetch:
    *connpool.ConnPool does not implement ConnPoolInterface (wrong type for GetConn method)
        have GetConn() connpool.Conn
        want GetConn() ConnInterface

有没有办法通过接口包装这个依赖,而不需要在每个文件中都导入连接池?

我需要它来模拟我的测试环境中的http请求,就像这样(如果我要在connpool包中实现接口,我将不得不在其中实现每个模拟结构,它看起来像是一团乱麻):

代码语言:javascript
运行
复制
package main

import(
  "testing"
)

type FakeConnPool struct{}

func (pool *FakeConnPool) GetConn() FakeConn {
    return FakeConn{}
}

func (pool *FakeConnPool) ReleaseConnection(conn FakeConn)  {
}

type FakeConn struct{}

func (c FakeConn) FetchUrl(url string) ([]byte, error) {
  println(url)
  body := []byte(`{"status" : 200}`)
    return body, nil
}

func changeDependency() ConnPoolInterface {
  return &FakeConnPool{}
}
func TestBaz(t *testing.T)  {
  pool := changeDependency()
    f := Fetcher{}
    err := f.Fetch(pool)
  if err != nil {
    t.Errorf("error")
  }
}
EN

回答 1

Stack Overflow用户

发布于 2016-04-18 16:13:57

作为第一步,只需将您的GetConn声明稍微更改为以下内容:

代码语言:javascript
运行
复制
func (pool *ConnPool) GetConn() ConnInterface {  // Conn -> ConnInterface
    return Conn{}
}

这应该可以完成ConnPoolInterface的接口。在此之后,您可能必须稍微重新安排代码,以避免循环依赖。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36688071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档