断言失败时可以调用函数吗?
例如,
assert.True(t, condition) // invoke a function such as printing a map
更新:根据建议,我写了一个小例子。但似乎不起作用。
assert.go
package main
import _ "fmt"
func compute() bool {
return false
}
assert_test.go
package main
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func pMap() {
amap := map[int]string{
1: "hello1",
2: "hello2",
}
for i, _ := range amap {
fmt.Println("map = ", i)
}
}
func TestCompute(t *testing.T) {
assert.True(t, compute(), pMap)
}
$ go测试
--- FAIL: TestCompute (0.00s)
assert_test.go:20:
Error Trace: assert_test.go:20
Error: Should be true
Test: TestCompute
Messages: 0x631a30
FAIL
exit status 1
答案 0 :(得分:0)
根据godoc,assert.True返回布尔值,因此您可以将其包装在条件中。 https://godoc.org/github.com/stretchr/testify/assert#True
passed := assert.True(t, compute()) // X will be a boolean true or false if the test passed.
您可以使用它来打印地图,就像这样:
if passed {
pMap()
} else {
// test failed
}