duanao2688
2017-03-13 23:33
浏览 23
已采纳

go中进行接口模拟的方法

If I have a handlerfunc like the one below. What is the best way to "mock" or inject a interface that wraps some object for testing?

func GetOrCreateUser(w http.ResponseWriter, r *http.Request) {
    user := GetUserFromContext(r.Context())
    if created :=user.GetOrCreate(); created {
        smtp.SendEmail(...)
        return
    } else {
        w.Write([]byte("Hello User!"))
    }
}

The only way that I have come by seems to be to do this:

type Mailer interface { SendMail() }

func HandlerWithMailer(m Mailer) http.handlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user := GetUserFromContext(r.Context())
        if created := user.GetOrCreate(); created {
            m.SendEmail(...)
            return
        } else {                
            w.Write([]byte("Hello User!"))
        }
    }
}

Then calling the mailer like this in the router (using httprouter):

m := mailer.New() // assuming this returns a new mailer
r := httprouter.New()
r.GET("/mailer", HandlerWithMailer(m))

Which could then be tested by making a struct that implements the interface and returns whatever I want, which can be called in the tests. I know this works, but I am wondering if this is the preferred method of testing in Go and if there is any other way to go about accomplishing this.

图片转代码服务由CSDN问答提供 功能建议

如果我有类似下面的处理函数。

  func GetOrCreateUser(w http.ResponseWriter,r * http.Request){\“是“模拟”或注入包装某些对象的接口的最佳方法是什么?  n用户:= GetUserFromContext(r.Context())
(如果已创建):= user.GetOrCreate(); 已创建{
 smtp.SendEmail(...)
返回
}其他{
 w.Write([] byte(“ Hello User!”))
} 
} 
  <  / pre> 
 
 

我遇到的唯一方法似乎是这样做:

  type Mailer接口{SendMail()} 
 \  nfunc HandlerWithMailer(m Mailer)http.handlerFunc {
 return func(w http.ResponseWriter,r * http.Request){
用户:= GetUserFromContext(r.Context())
如果创建了:= user.GetOrCreate(  ); 创建了{
 m.SendEmail(...)
 return 
}否则{
 w.Write([] byte(“ Hello User!”))
} 
} 
} 
   
 
 

然后在路由器(使用httprouter)中这样调用邮件程序:

  m:= mailer.New()/  /假设这会返回一个新的mailer 
r:= httprouter.New()
r.GET(“ / mailer”,HandlerWithMailer(m))
   
 
 

然后通过构造实现该接口并返回我想要的任何内容的结构进行测试,可以在测试中调用该结构。 我知道这可行,但是我想知道这是否是Go中首选的测试方法,是否还有其他方法可以实现这一目标。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题