gomega 简述

What is?

gomega 可以判断变量的值是否符合预期,进行判断后将failed发送给ginkgo之类的测试框架进行处理。简单来说就是封装类似deepequal(a, b) 之类的方法,减少自己编写的测试代码行数。

how to use?

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)

创建断言(assertion)

可以使用Ω或者Expect创建最简单的assertion,这两种写法具有相同的意义。ShouldToShouldNotNoToToNot也具有相同意义。

Ω(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
}

how to learn?

对于ginkgo以及gomega我都推荐去阅读官方文档(https://onsi.github.io/gomega/),相比搜索引擎中的其他结果更加清晰易懂。

updatedupdated2023-03-022023-03-02