英文:
Testing Golang imported function is called?
问题
假设我在 main.go
文件中有以下代码:
package main
import "foobar"
func moo() {
foobar.Boom("!")
}
func main() {
moo()
}
我该如何对 Boom
进行桩测试(stub)并确保它被正确调用了?
英文:
Say I have in main.go
package main
import "foobar"
func moo() {
foobar.Boom("!")
}
func main() {
moo()
}
How do I stub out Boom
and make sure it was called with the correct parameters?
答案1
得分: 1
Go的方式是使用接口,即使你无法更改foobar包。
1)创建一个boomer接口
type Boomer interface{
Boom(string)
}
2)修改moo()函数,使其接受boomer参数
func moo(b Boomer) {
b.Boom("!")
}
3)添加一个包含foobar的变量
在playground中,我使用以下结构。但是在外部包中,你可以使用foobar.Boom()代替Println。
type foobar struct{}
func (fb foobar) Boom(s string) {
fmt.Println(s)
}
var f Boomer = foobar{}
https://play.golang.org/p/200WIok1pL
4)在你的测试中实现一个测试boomer
type testboomer struct{
boomstring string
}
func (tb *testboomer) Boom(s string) {
tb.boomstring = s
}
在调用moo()函数之后,testboomer.boomstring将显示其值。
英文:
The Go-way would be to use an interface. Even if you are not able to change the foobar package.
1) create a boomer interface
type Boomer interface{
Boom(string)
}
2) change moo() that it accepts the boomer
func moo(b Boomer) {
b.Boom("!")
}
3) add a variable with the foobar
For the playground I use the following construct. But with a extern package you can use the foobar.Boom() instead of Println
type foobar struct{}
func (fb foobar) Boom(s string) {
fmt.Println(s)
}
var f Boomer = foobar{}
https://play.golang.org/p/200WIok1pL
4) Inside your test you implement a test boomer
type testboomer struct{
boomstring string
}
func (tb *testboomer) Boom(s string) {
tb.boomstring = s
}
After you called the moo() function the testboomer.boomstring shows the value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论