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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化