有没有一种方法可以在 testify 中链接多个断言?

huangapple go评论82阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2017年3月28日 14:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/43061814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定