登录
首页 >  Golang >  Go问答

测试函数是否被调用

来源:stackoverflow

时间:2024-04-08 13:15:27 262浏览 收藏

一分耕耘,一分收获!既然都打开这篇《测试函数是否被调用》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

给定这个结构和函数:

type ExampleModule struct {
  DB                   *database.Store
  AnotherModule        AnotherModuleInterface
}

func(m *ExampleModule) A (i int, id int[]) error{
  err := m.AnotherModuke.SomeFunc(i, id)
}

如何进行单元测试以确保在运行函数 a 时调用 somefunc


解决方案


  1. 您可以模拟接口的实现,例如
globalIndex
type Mock struct{}

func (m Mock) SomeFunc(){
    globalIndex++
}

func testA(t *testing.T) {
    a := ExampleModule{
        AnotherModule: Mock{},
    }
    a.A()
    assert(globalIndex == 1)
}

  1. 尝试 testifyassertexpectations 可以帮助你

https://github.com/stretchr/testify#mock-package

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>