登录
首页 >  Golang >  Go问答

在Go中模拟对象A和B,当A的方法返回B

来源:stackoverflow

时间:2024-03-20 15:33:29 178浏览 收藏

在 Go 中进行单元测试时,为了避免依赖外部服务,需要模拟对象。可以使用接口和模拟结构来实现此目的。通过将主代码中的服务函数更改为使用接口,并在测试中使用接口的模拟实现,可以对服务功能进行单元测试,而无需连接到外部服务。这种方法允许对服务进行独立测试,并提高测试的可维护性。

问题内容

我正在尝试在 go 中为现有服务实现单元测试,该服务使用连接池结构和现有库中的连接结构(称为 librarypoollibraryconnection)来连接到外部服务。 为了使用这些,主代码中的服务函数使用池的唯一全局实例,该实例具有 getconnection() 方法,如下所示:

// current main code
var pool librarypool // global, instantiated in main()

func someservicefunction(w http.responsewriter, r *http.request) {
  // read request
  // ...
  conn := pool.getconnection()
  conn.do("some command")
  // write response
  // ... 
}

func main() {
  pool := makepool() // builds and returns a librarypool
  // sets up endpoints that use the service functions as handlers
  // ...
}

我想在不连接到外部服务的情况下对这些服务功能进行单元测试,因此我想模拟 librarypool 和 libraryconnection。为了实现这一点,我正在考虑将主代码更改为如下所示:

// Tentative New Main Code
type poolInterface interface {
  GetConnection() connInterface
}

type connInterface interface {
  Do(command string)
}

var pool poolInterface

func someServiceFunction(w http.ResponseWriter, r *http.Request) {
  // read request
  // ...
  conn := pool.GetConnection()
  conn.Do("some command")
  // write response
  // ...
}

func main() {
  pool := makePool() // still builds a LibraryPool
}

在测试中,我将使用这些接口的模拟实现 mockpoolmockconnection,并且全局 pool 变量将使用 mockpool 实例化。我将在 testmain() 函数内部的 setup() 函数中实例化这个全局 pool

问题在于,在新的主代码中,librarypool 没有正确实现 poolinterface,因为 getconnection() 返回 conninterface 而不是 libraryconnection(即使 zqbcz qblibraryconnection 是 conninterface 的有效实现) .

进行此类测试的好方法是什么?顺便说一句,主要代码也很灵活。


解决方案


好吧,我会尝试通过完整解释我如何看待这个设计来回答。如果这太多而且不切中要害,请提前抱歉..

  • 实体/域
    • 应用程序的核心,将包含实体结构,不会导入任何外层包,但可以被每个包导入(几乎)
  • 应用/用例
    • “服务”。将主要负责应用程序逻辑,不会了解传输(http),将通过接口与数据库“对话”。在这里您可以进行域验证,例如如果找不到资源或文本太短。任何与业务逻辑相关的内容。
  • 交通
    • 将处理http请求,解码请求,让服务完成他的工作,并对响应进行编码。如果请求中缺少必需的参数,或者用户没有被授权,或者其他什么,你可以在这里返回 401...
  • 基础设施
    • 数据库连接
    • 也许是一些 http 引擎和路由器之类的东西。
    • 完全与应用程序无关,不要导入任何内部包,甚至 pseron 也不要导入

例如,假设我们想做一些简单的事情,例如将 person 插入数据库。

包 person 将仅包含 person 结构

package person

type person struct{
  name string
}

func new(name string) person {
  return person{
    name: name,
  {
}

关于数据库,假设您使用sql,我建议制作一个名为 sql 的包来处理存储库。 (如果您使用 postgress,请使用“postgress 包...”)。

personrepo将获取dbconnection,该dbconnection将在main中初始化并实现dbandler。只有连接才会直接与数据库“对话”,存储库的主要目标是成为数据库的网关,并以应用程序术语进行对话。 (连接与应用程序无关)

package sql

type dbandler interface{
  exec(string, ...interface{}) (int64, error)
}

type personrepo struct{
  dbhandler dbhandler
}

func newpersonrepo(dbhandler dbhandler) &personrepo {
  return &personrepo{
    dbhandler: dbhandler,
  }
}

func (p *personrepo) insertperson(p person.person) (int64, error) {
  return p.dbhandler.exec("command to insert person", p)
}

该服务将将此存储库作为初始化程序中的依赖项(作为接口)获取,并将与其交互以完成业务逻辑

package service

type personrepo interface{
  insertperson(person.person) error
}

type service struct {
  repo personrepo
}

func new(repo personrepo) *service {
  return &service{
    repo: repo
  }
}

func (s *service) addperson(name string) (int64, error) {
  person := person.new(name)
  return s.repo.insertperson(person)
}

您的传输处理程序将使用该服务作为依赖项进行初始化,并且他将处理 http 请求。

package http

type service interface{
  addperson(name string) (int64, error)
}

type handler struct{
  service service
}

func newhandler(s service) *handler {
  return &handler{
    service: s,
  }
}

func (h *handler) handlehttp(w http.responsewriter, r *http.request) {
  // read request
  // decode name

  id, err := h.service.addperson(name)

  // write response
  // ... 
}

在 main.go 中,您将把所有内容联系在一起:

  1. 初始化数据库连接
  2. 使用此连接初始化 personrepo
  3. 使用存储库初始化服务
  4. 使用服务初始化传输

主包

func main() {
  pool := makePool()
  conn := pool.GetConnection()

  // repo
  personRepo := sql.NewPersonRepo(conn)

  // service
  personService := service.New(personRepo)

  // handler
  personHandler := http.NewPersonHandler(personService)

  // Do the rest of the stuff, init the http engine/router by passing this handler.

}

请注意,每个包结构都使用 interface 进行初始化,但返回 struct,并且接口也是在使用它们的包中声明的,而不是在实现它们的包中声明的。

这使得对这些包进行单元测试变得很容易。例如,如果你想测试服务,你不需要担心http请求,只需使用一些实现服务依赖的接口(personrepo)的“模拟”结构,然后你就可以开始了。

好吧,我希望它对您有一点帮助,一开始可能看起来很混乱,但随着时间的推移,您会发​​现这看起来像是一大段代码,但当您需要添加功能或切换db 驱动程序等...我建议您阅读有关 go 中的领域驱动设计以及六角形拱门的内容。

编辑:

此外,通过这种方式,您传递与服务的连接,该服务不会导入和使用全局数据库池。老实说,我不知道为什么它如此常见,我想它有它的优点,并且对某些应用程序来说更好,但一般来说,我认为让您的服务依赖于某些接口,而不真正知道发生了什么,这是很重要的更好的做法。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在Go中模拟对象A和B,当A的方法返回B》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>