gpt4 book ai didi

go - 断言失败触发函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:56 25 4
gpt4 key购买 nike

我可以在断言失败时调用函数吗?

例如,

assert.True(t, condition) // invoke a function such as printing a map

更新:根据建议,我写了一个小例子。但似乎不起作用。

断言.go

package main                                                                     

import _ "fmt"

func compute() bool {
return false
}

断言测试.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)
}

$去测试

--- 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

最佳答案

根据 godoc,assert.True 返回一个 bool 值,因此您可以将其包装在条件中。 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.  

您可以使用它来打印 map /任何类似的东西:

if  passed {
pMap()
} else {
// test failed
}

关于go - 断言失败触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com