英文:
Golang testing with functions
问题
我正在使用一个第三方库,它是一些C函数的包装器。不幸的是,几乎所有的Go函数都是自由的(它们没有接收器,它们不是方法);这不是我会采取的设计方法,但这就是我现在的情况。
只使用Go的标准"testing"库:
是否有一种解决方案可以让我创建可以模拟函数的测试?
还是将库封装到结构体和接口中,然后模拟接口来实现我的目标是解决方案?
我创建了一个蒙特卡洛模拟,还处理生成的数据集。我的一个评估算法会寻找特定的模型,然后将其传递给第三方函数进行评估。我知道我的边界情况,并知道调用次数应该是什么,这就是我想要测试的内容。
也许只需要一个简单的计数器?
我找到的使用这个库的其他项目,没有完全覆盖或根本没有测试。
英文:
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
得分: 0
你可以通过在需要调用函数的地方使用对实际函数的引用来实现这一点。
然后,当你需要模拟函数时,只需将引用指向模拟实现即可。
假设这是你的外部函数:
// 这是一个外部函数的包装器
func externalFunction(i int) int {
return i * 10 // 对输入进行一些操作
}
你不直接调用它,而是声明一个对它的引用:
var processInt func(int) int = externalFunction
当你需要调用该函数时,使用引用来执行:
fmt.Println(processInt(5))
然后,当你想要模拟函数时,只需将模拟实现赋值给该引用:
processInt = mockFunction
这个示例将它们放在一起,可能比解释更清楚:
https://play.golang.org/p/xBuriFHlm9
如果你有一个接收 func(int) int
的函数,当你希望它使用模拟实现时,可以将该函数发送给实际的 externalFunction
或 mockFunction
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论