英文:
Is there a way to chain asserts with testify?
问题
我非常喜欢go test
中的testify
带来的好处。然而,我查阅了文档,没有找到如何处理多个断言的说明。
在Go中,它会处理“第一个失败”,也就是说,如果有一个断言失败,它会在第一个失败的地方停止,而不会继续执行后面的断言。它只关注测试方法中的最后一个断言。
英文:
I really like what testify brings to go test
. However, I dug through the documentation and didn't see anything on how to handle multiple asserts.
Does Go handle "first failure", in the sense it fails at the first bad assert, or will it only concern itself with the last assert in the test method?
答案1
得分: 9
你可以使用testify/require,它与assert具有完全相同的接口,但在失败时终止执行。http://godoc.org/github.com/stretchr/testify/require
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestWithRequire(t *testing.T) {
require.True(t, false) // 失败并终止执行
require.True(t, true) // 永远不会执行
}
func TestWithAssert(t *testing.T) {
assert.True(t, false) // 失败
assert.True(t, false) // 也会失败
}
英文:
You can use testify/require which has the exact same interface as assert, but it terminates the execution on failure. http://godoc.org/github.com/stretchr/testify/require
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
)
func TestWithRequire(t *testing.T) {
require.True(t, false) // fails and terminates
require.True(t, true) // never executed
}
func TestWithAssert(t *testing.T) {
assert.True(t, false) // fails
assert.True(t, false) // fails as well
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论