gomega 可以判断变量的值是否符合预期,进行判断后将failed发送给ginkgo之类的测试框架进行处理。简单来说就是封装类似deepequal(a, b) 之类的方法,减少自己编写的测试代码行数。
just import
1
2
3
|
import "github.com/onsi/gomega"
//or
import . "github.com/onsi/gomega"
|
set a GomegaFailHandler
to handle a Gomega assertion fails.
1
2
|
//in ginkgo
gomega.RegisterFailHandler(ginkgo.Fail)
|
可以使用Ω或者Expect创建最简单的assertion,这两种写法具有相同的意义。Should
与To
,ShouldNot
与NoTo
、ToNot
也具有相同意义。
Ω(ACTUAL).Should(Equal(EXPECTED))
Ω(ACTUAL).ShouldNot(Equal(EXPECTED))
Expect(ACTUAL).To(Equal(EXPECTED))
Expect(ACTUAL).NotTo(Equal(EXPECTED))
Expect(ACTUAL).ToNot(Equal(EXPECTED))
ACTUAL
即需要进行断言的值,右侧should
之类的方法需要传参GomegaMatcher
(接口),例子中Equal(EXPECTED)
就会返回一个该类型的obj。该对象的Match
方法包装了deepequal
判断ACTUAL和EXPECTED是否相同。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) {
if actual == nil && matcher.Expected == nil {
return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.")
}
// Shortcut for byte slices.
// Comparing long byte slices with reflect.DeepEqual is very slow,
// so use bytes.Equal if actual and expected are both byte slices.
if actualByteSlice, ok := actual.([]byte); ok {
if expectedByteSlice, ok := matcher.Expected.([]byte); ok {
return bytes.Equal(actualByteSlice, expectedByteSlice), nil
}
}
return reflect.DeepEqual(actual, matcher.Expected), nil
}
|
对于ginkgo以及gomega我都推荐去阅读官方文档(https://onsi.github.io/gomega/),相比搜索引擎中的其他结果更加清晰易懂。