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.

  • 写回答

1条回答 默认 最新

  • dsv768456 2017-03-14 03:26
    关注

    I would call my handlers from a struct like so:

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

    This way you can instansiate the struct with the implementation of Mailer you want to use.

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

    and in your tests

    m := mockMailer.New() // assuming this returns a new mailer
    h := Handlers{&m}
    
    r := httprouter.New()
    r.GET("/mailer", h.HandlerWithMailer)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名