英文:
Go: mock return value of a function in unit test
问题
我已经在golang中创建了一个小脚本(我的第一个golang项目)。
示例:
package main
import (
"fmt"
"math/rand"
)
func main() {
i := rand.Intn(10)
foo := foo(i)
if foo {
fmt.Printf("%d是偶数!", i)
// 更多代码...
} else {
fmt.Printf("%d是奇数!", i)
// 更多代码...
}
}
func foo(i int) bool {
if i%2 == 0 {
return true
} else {
return false
}
}
我想为每个函数创建一个小的单元测试。
对于"main()"函数,我想模拟函数"foo()"的返回值,因为我不想测试"foo()",而是测试main()函数的其余代码。
我正在寻找一种简单的方法来存根/模拟返回值。
我只找到了使用结构体或接口等进行模拟。但是我在代码中没有使用这些元素(这是一个简单的项目)。
英文:
I have created a small script in golang (my first golang project).
Example:
package main
import (
"fmt"
"math/rand"
)
func main() {
i := rand.Intn(10)
foo := foo(i)
if foo {
fmt.Printf("%d is even!", i)
// more code ...
} else {
fmt.Printf("%d is odd!", i)
// more code ...
}
}
func foo(i int) bool {
if i%2 == 0 {
return true
} else {
return false
}
}
I would like to create a small unit test for each function.
For "main()", I want to mock the return value of function "foo()", because I won't test "foo()", but the rest of main()-code.
I'm looking for an easy way to stub/mock the return value.
I just found mocks with struct or interaces etc. But I didn't use these elements in code (it's a simple project).
答案1
得分: 3
使用一个真实、简洁、可重现的示例:如何创建一个简洁、可重现的示例。
例如,在Go语言中:
package main
import (
"fmt"
"math/rand"
)
func isEven(i int) bool {
return i%2 == 0
}
func side(n int) string {
if isEven(n) {
return "right"
} else {
return "left"
}
}
func main() {
n := 1 + rand.Intn(10)
hand := side(n)
fmt.Printf("Number %d is on the %s-hand side of the street.\n", n, hand)
}
https://go.dev/play/p/a0SudgaRCnu
输出结果为:
Number 9 is on the left-hand side of the street.
使用Go的testing包对side
函数进行单元测试。你也可以直接对isEven
函数进行单元测试。main
函数不应包含任何你想要进行单元测试的代码。
package main
import (
"testing"
)
func TestSide(t *testing.T) {
n := 7
got := side(n)
want := "left"
if got != want {
t.Errorf("side(%d) = %s; want %s", n, got, want)
}
}
英文:
Use a realistic, minimal, reproducible example: How to create a Minimal, Reproducible Example.
For example, in Go,
package main
import (
"fmt"
"math/rand"
)
func isEven(i int) bool {
return i%2 == 0
}
func side(n int) string {
if isEven(n) {
return "right"
} else {
return "left"
}
}
func main() {
n := 1 + rand.Intn(10)
hand := side(n)
fmt.Printf("Number %d is on the %s-hand side of the street.\n", n, hand)
}
https://go.dev/play/p/a0SudgaRCnu
Number 9 is on the left-hand side of the street.
Use the Go testing package to unit test the side
function. You might also unit test the isEven
function directly. The main
function should not contain any code that you want to unit test.
package main
import (
"testing"
)
func TestSide(t *testing.T) {
n := 7
got := side(n)
want := "left"
if got != want {
t.Errorf("side(%d) = %s; want %s", n, got, want)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论