在軟件開發中,單元測試是一項非常重要的工作,它可以幫助開發者確保代碼的質量和可靠性。而在Go語言中,我們可以使用一些庫和技術來模擬函數的返回值,以便更好地進行單元測試。本文將由php小編小新為大家介紹Go語言中實現函數模擬返回值的方法,幫助開發者更好地進行單元測試,提高代碼的質量和可維護性。
問題內容
我在 golang 中創建了一個小腳本(我的第一個 golang 項目)。
示例:
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
}
}
登錄后復制
我想為每個函數創建一個小型單元測試。
對于“main()”,我想模擬函數“foo()”的返回值,因為我不會測試“foo()”,而是測試main()代碼的其余部分。
我正在尋找一種簡單的方法來存根/模擬返回值。
我剛剛發現了帶有結構或接口等的模擬。但我沒有在代碼中使用這些元素(這是一個簡單的項目)。
解決方法
使用一個現實的、最小的、可重現的示例:如何創建一個最小的、可重現的示例。
例如,在 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://www.php.cn/link/7c63a554c36ea63c77723a472b7ca20f
number 9 is on the left-hand side of the street.
登錄后復制
使用go測試包對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)
}
}
登錄后復制






