测试 Golang 导入的函数是否被调用?

huangapple go评论129阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年7月21日 02:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/38488316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定