duanqianhuan3994 2017-09-15 18:30
浏览 38
已采纳

使用功能进行Golang测试

I am using a third-party library that is a wrapper over some C functions. Unfortunately, nearly all of the Go functions are free (they don't have a receiver, they are not methods); not the design approach I would have taken but it is what I have.

Using just Go's standard "testing" library:

Is there a solution that allows me to create tests where I can mock functions?

Or is the solution to wrap the library into structures and interfaces, then mock the interface to achieve my goal?


I have created a monte carlo simulation that also process the produced dataset. One of my evaluation algorithms looks for specific models that it then passes the third-party function for its evaluation. I know my edge cases and know what the call counts should be, and this is what I want to test.

Perhaps a simple counter is all that is needed?


Other projects using this library, that I have found, do not have full coverage or no testing at all.

  • 写回答

1条回答 默认 最新

  • duangan2307 2017-09-15 19:58
    关注

    You can do this by using a reference to the actual function whenever you need to call it.

    Then, when you need to mock the function you just point the reference to a mock implementation.

    Let's say this is your external function:

    // this is the wrapper for an external function
    func externalFunction(i int) int {
       return i * 10  // do something with input
    }
    

    You never call this directly but instead declare a reference to it:

    var processInt func(int) int = externalFunction
    

    When you need to invoke the function you do it using the reference:

    fmt.Println(processInt(5))
    

    Then, went you want to mock the function you just assign a mock implementation to that reference:

    processInt = mockFunction
    

    This playground puts it together and might be more clear than the explanation:

    https://play.golang.org/p/xBuriFHlm9

    If you have a function that receives a func(int) int, you can send that function either the actual externalFunction or the mockFunction when you want it to use the mock implementation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等