dongwu8064 2018-09-18 07:40
浏览 74

测试Golang处理程序中是否调用了该方法

I am implementing a API in Golang. I have a endpoint where I am calling a method with parameters of other package. Now I need to check that, that method has been called in the request.

Below is the small similar scenario what I am doing and what I am expecting.

My handler

package myPackage
import (
    "log"
    "github.com/myrepo/notifier" // my another package
)

func MyHandler(writer http.ResponseWriter, request *http.Request) { 
    // ...
    // ...

    notifier.Notify(4, "sdfsdf")

    // ...
    // ...

}

Testing handler

func TestMyHandler(t *testing.T) {
    // Here I want to 
    req, _ := http.NewRequest("GET", "/myendpoint", nil)
    // ... Want to test that notifier.Notify is called
    // ...
}

In the TestMyHandler, I want to check that notifier.Notify has called.

Findings

I tried to understand the AssertNumberOfCalls, func (*Mock) Called, and func (*Mock) MethodCalled but I am not sure how to use them :(.

I am a newbie in Golang and really exicted to do that. Please let me know if I missed anything or you may need more information for more understaing.

  • 写回答

2条回答 默认 最新

  • dongmi4734 2018-09-18 08:01
    关注

    Want to test that notifier.Notify is called.

    No you don't. You are interested in that the handler does what it should do and this seems to consist of two things:

    1. Return the right response (easy to test with a net/http/httptest.ResponseRecorder), and

    2. Has some noticeable side effect, here issue some notification.

    To test 2. you test that the notification was issued, not that some function was called. Whatever notify.Notify results in (e.g. a database entry, a file, some HTTP call) should be tested. Formally this is no longer unit testing but testing for side effects is never strict unit testing.

    What you can do: Wrap your handler logic into some object and observe that objects state. Ugly. Don't.

    评论

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”