如何在不使用依赖注入的情况下从另一个包中模拟一个函数? [英] How do I mock a function from another package without using dependency injection?
问题描述
有点像golang的初学者,但是我之前已经使用过测试框架.我该如何模拟并伪造从属方法返回的结果而不注入该从属关系?我不想使用依赖项注入的原因是因为有许多外部包方法正在使用,并且将所有方法注入构造函数中都很麻烦.
Somewhat of a golang beginner, but I've worked with testing frameworks before. How do I go about mocking out and faking what a dependent method returns without injecting the dependency? The reason why I don't want to use dependency injection is because there are many external package methods that are being used and injecting all of the methods in the constructor is unwieldy.
我已经搜索了此在线/堆栈溢出,并且解决方案是始终使用依赖项注入.有时这不是一个可行的选择.
I've searched for this online/stackoverflow and the solution is to always use dependency injection. Sometimes that is not a viable option.
这就是我要在代码方面做的事情:
Here's what I'm trying to do code-wise:
b/b_test.go
b/b_test.go
package b
func TestResults(t *testing.T) {
t.Run("Test", func(t *testing.T) {
b := NewB()
// How do I mock out and fake a.DoSomething() to be
// "complete" instead of whats in the code right now?
result = b.Results()
assert.Equal(t, "complete", result)
}
}
b/b.go
package b
import "a"
type B struct {}
func NewB() B {
return &B{}
}
func (b B) Results() {
return a.DoSomething()
}
a/a.go
package a
func DoSomething() {
return "done"
}
谢谢!
推荐答案
您可以使用使用构建标签进行条件编译
a/a.go
// +build !mock
package a
func DoSomething() {
return "done"
}
a/a_mock.go
a/a_mock.go
// +build mock
package a
func DoSomething() { // Insert fake implementation here
return "complete"
}
$ 去测试-tags模拟
这篇关于如何在不使用依赖注入的情况下从另一个包中模拟一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!