Gomega provides 70+ built-in matchers for common testing scenarios. All matchers implement the types.GomegaMatcher interface and can be used with Expect(), Eventually(), and Consistently() assertions.
import . "github.com/onsi/gomega"func Equal(expected any) types.GomegaMatcher { .api }Deep equality using reflect.DeepEqual. Strict type and value matching.
Example:
Expect(actual).To(Equal(expected))
Expect([]int{1, 2, 3}).To(Equal([]int{1, 2, 3}))func BeEquivalentTo(expected any) types.GomegaMatcher { .api }Lax equality with type conversion. Allows numeric type coercion.
Example:
Expect(5).To(BeEquivalentTo(5.0)) // int to float64
Expect(uint(5)).To(BeEquivalentTo(5)) // uint to intfunc BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { .api }Uses go-cmp library for customizable deep equality with options.
Example:
Expect(actual).To(BeComparableTo(expected))
Expect(actual).To(BeComparableTo(expected, cmpopts.IgnoreFields(MyStruct{}, "ID")))func BeIdenticalTo(expected any) types.GomegaMatcher { .api }Pointer/reference equality using == operator. Checks if two values point to the same memory location.
Example:
ptr1 := &myStruct
ptr2 := ptr1
Expect(ptr1).To(BeIdenticalTo(ptr2))func BeNil() types.GomegaMatcher { .api }Checks if value is nil.
Example:
var err error
Expect(err).To(BeNil())func BeZero() types.GomegaMatcher { .api }Checks if value is the zero value for its type.
Example:
Expect(0).To(BeZero())
Expect("").To(BeZero())
Expect([]int{}).To(BeZero())func BeTrue() types.GomegaMatcher { .api }Checks if value is boolean true.
Example:
Expect(true).To(BeTrue())func BeFalse() types.GomegaMatcher { .api }Checks if value is boolean false.
Example:
Expect(false).To(BeFalse())func BeTrueBecause(format string, args ...any) types.GomegaMatcher { .api }Checks for true with formatted reason message displayed on failure.
Example:
Expect(isValid).To(BeTrueBecause("validation should pass for user %s", username))func BeFalseBecause(format string, args ...any) types.GomegaMatcher { .api }Checks for false with formatted reason message displayed on failure.
Example:
Expect(isEnabled).To(BeFalseBecause("feature flag should be disabled in test"))func HaveOccurred() types.GomegaMatcher { .api }Checks if error is non-nil.
Example:
err := doSomething()
Expect(err).Should(HaveOccurred())func Succeed() types.GomegaMatcher { .api }Checks if error is nil (inverse of HaveOccurred).
Example:
Expect(doSomething()).Should(Succeed())func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { .api }Matches error against string, regex, matcher, error type, or error value. Uses errors.Is() and reflect.DeepEqual.
Example:
Expect(err).To(MatchError("connection failed"))
Expect(err).To(MatchError(ContainSubstring("timeout")))
Expect(err).To(MatchError(io.EOF))
Expect(err).To(MatchError(os.IsNotExist, "IsNotExist"))func ContainSubstring(substr string, args ...any) types.GomegaMatcher { .api }Checks if string contains substring. Supports format args via fmt.Sprintf.
Example:
Expect("Hello World").To(ContainSubstring("World"))
Expect(output).To(ContainSubstring("error: %s", expectedError))func HavePrefix(prefix string, args ...any) types.GomegaMatcher { .api }Checks if string starts with prefix. Supports format args.
Example:
Expect("Hello World").To(HavePrefix("Hello"))
Expect(filename).To(HavePrefix("test_"))func HaveSuffix(suffix string, args ...any) types.GomegaMatcher { .api }Checks if string ends with suffix. Supports format args.
Example:
Expect("Hello World").To(HaveSuffix("World"))
Expect(filename).To(HaveSuffix(".json"))func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { .api }Matches string against regular expression. Supports format args.
Example:
Expect("123-456").To(MatchRegexp(`\d{3}-\d{3}`))
Expect(email).To(MatchRegexp(`^[a-z]+@[a-z]+\.[a-z]+$`))func BeEmpty() types.GomegaMatcher { .api }Checks if collection (slice, array, map, channel, string) is empty.
Example:
Expect([]int{}).To(BeEmpty())
Expect("").To(BeEmpty())
Expect(make(map[string]int)).To(BeEmpty())func HaveLen(count int) types.GomegaMatcher { .api }Checks if collection has specific length.
Example:
Expect([]int{1, 2, 3}).To(HaveLen(3))
Expect("hello").To(HaveLen(5))func HaveCap(count int) types.GomegaMatcher { .api }Checks if collection has specific capacity.
Example:
slice := make([]int, 3, 10)
Expect(slice).To(HaveCap(10))func ContainElement(element any, result ...any) types.GomegaMatcher { .api }Checks if collection contains element. Element can be value or matcher. Optional result pointer captures matched element(s).
Example:
Expect([]string{"Foo", "Bar"}).To(ContainElement("Foo"))
Expect([]string{"Foo", "FooBar"}).To(ContainElement(ContainSubstring("Bar")))
var found string
Expect([]string{"Foo", "Bar"}).To(ContainElement("Bar", &found))func ContainElements(elements ...any) types.GomegaMatcher { .api }Checks if collection contains all specified elements. Order doesn't matter.
Example:
Expect([]string{"Foo", "Bar", "Baz"}).To(ContainElements("Foo", "Bar"))
Expect([]int{1, 2, 3, 4}).To(ContainElements(2, 4))func ConsistOf(elements ...any) types.GomegaMatcher { .api }Checks if collection contains exactly the specified elements (no more, no less). Order doesn't matter.
Example:
Expect([]string{"Foo", "Bar"}).To(ConsistOf("Bar", "Foo"))
Expect([]string{"Foo", "FooBar"}).To(ConsistOf(ContainSubstring("Bar"), "Foo"))func HaveExactElements(elements ...any) types.GomegaMatcher { .api }Checks if collection matches elements in exact order.
Example:
Expect([]string{"Foo", "Bar"}).To(HaveExactElements("Foo", "Bar"))
Expect([]int{1, 2, 3}).To(HaveExactElements(1, BeNumerically(">", 1), 3))func HaveEach(element any) types.GomegaMatcher { .api }Checks if all elements in collection match the matcher or value. Fails if collection is empty.
Example:
Expect([]string{"FooBar", "FooBaz"}).To(HaveEach(ContainSubstring("Foo")))
Expect([]int{2, 4, 6}).To(HaveEach(BeNumerically("%", 2, 0)))func BeElementOf(elements ...any) types.GomegaMatcher { .api }Checks if value is an element of the provided collection (reverse containment).
Example:
Expect(2).To(BeElementOf([]int{1, 2, 3}))
Expect(2).To(BeElementOf(1, 2, 3))func HaveKey(key any) types.GomegaMatcher { .api }Checks if map contains key. Key can be value or matcher.
Example:
Expect(map[string]int{"foo": 1}).To(HaveKey("foo"))
Expect(map[string]string{"FooBar": "val"}).To(HaveKey(ContainSubstring("Foo")))func HaveKeyWithValue(key any, value any) types.GomegaMatcher { .api }Checks if map has key-value pair. Both can be values or matchers.
Example:
Expect(map[string]int{"foo": 42}).To(HaveKeyWithValue("foo", 42))
Expect(map[string]string{"foo": "bar"}).To(HaveKeyWithValue("foo", ContainSubstring("ar")))func BeKeyOf(element any) types.GomegaMatcher { .api }Checks if value is a key in the map (reverse key check).
Example:
Expect("foo").To(BeKeyOf(map[string]bool{"foo": true, "bar": false}))func HaveField(field string, expected any) types.GomegaMatcher { .api }Checks if struct field matches value or matcher. Field path supports nesting with dots and method calls with ().
Example:
Expect(book).To(HaveField("Title", "Les Miserables"))
Expect(book).To(HaveField("Author.FirstName", "Victor"))
Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900)))func HaveExistingField(field string) types.GomegaMatcher { .api }Checks if struct has field without checking its value.
Example:
Expect(user).To(HaveExistingField("Email"))
Expect(config).NotTo(And(HaveExistingField("Secret"), HaveField("Secret", BeEmpty())))func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { .api }Dereferences pointer (repeatedly if needed) and matches the value. Works with interfaces too.
Example:
actual := 42
Expect(&actual).To(HaveValue(Equal(42)))
Expect(&&actual).To(HaveValue(Equal(42)))func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { .api }Numeric comparison. Comparators: "==", "~" (within threshold), ">", ">=", "<", "<=".
Example:
Expect(1.0).To(BeNumerically("==", 1))
Expect(1.0).To(BeNumerically("~", 0.999, 0.01))
Expect(5).To(BeNumerically(">", 3))
Expect(5).To(BeNumerically(">=", 5))func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { .api }Time comparison using same comparators as BeNumerically.
Example:
Expect(time.Now()).To(BeTemporally(">", time.Time{}))
Expect(time.Now()).To(BeTemporally("~", time.Now(), time.Second))func BeAssignableToTypeOf(expected any) types.GomegaMatcher { .api }Checks if value's type is assignable to expected type.
Example:
Expect(5).To(BeAssignableToTypeOf(0))
Expect("foo").To(BeAssignableToTypeOf("bar"))func Panic() types.GomegaMatcher { .api }Checks if function panics when called. Actual must be a no-arg, no-return function.
Example:
Expect(func() { panic("boom") }).To(Panic())func PanicWith(expected any) types.GomegaMatcher { .api }Checks if function panics with specific value. Expected can be value or matcher.
Example:
Expect(func() { panic("boom") }).To(PanicWith("boom"))
Expect(func() { panic("error: timeout") }).To(PanicWith(ContainSubstring("timeout")))func BeClosed() types.GomegaMatcher { .api }Checks if channel is closed. Must read from channel to test.
Example:
ch := make(chan int)
close(ch)
Expect(ch).To(BeClosed())func Receive(args ...any) types.GomegaMatcher { .api }Checks if channel has value to receive. Never blocks. Optional args: matcher for value, pointer to capture value.
Example:
ch := make(chan string, 1)
ch <- "hello"
Expect(ch).To(Receive())
var received string
Eventually(ch).Should(Receive(&received))
Eventually(ch).Should(Receive(Equal("hello")))func BeSent(arg any) types.GomegaMatcher { .api }Checks if value can be sent to channel (channel ready to receive). Never blocks.
Example:
ch := make(chan string, 1)
Expect(ch).To(BeSent("hello"))
Eventually(ch).Should(BeSent("data"))func BeAnExistingFile() types.GomegaMatcher { .api }Checks if file or directory exists. Actual must be string path.
Example:
Expect("/tmp/myfile.txt").To(BeAnExistingFile())func BeARegularFile() types.GomegaMatcher { .api }Checks if path is a regular file (not directory or special file). Actual must be string path.
Example:
Expect("/tmp/myfile.txt").To(BeARegularFile())func BeADirectory() types.GomegaMatcher { .api }Checks if path is a directory. Actual must be string path.
Example:
Expect("/tmp").To(BeADirectory())func HaveHTTPStatus(expected ...any) types.GomegaMatcher { .api }Matches HTTP response status code. Accepts int or status string. Can match multiple status codes.
Example:
Expect(resp).To(HaveHTTPStatus(http.StatusOK))
Expect(resp).To(HaveHTTPStatus(200))
Expect(resp).To(HaveHTTPStatus("404 Not Found"))
Expect(resp).To(HaveHTTPStatus(http.StatusOK, http.StatusNoContent))func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher { .api }Checks if HTTP response has header with specific value. Value can be string or matcher.
Example:
Expect(resp).To(HaveHTTPHeaderWithValue("Content-Type", "application/json"))
Expect(resp).To(HaveHTTPHeaderWithValue("Content-Type", ContainSubstring("json")))func HaveHTTPBody(expected any) types.GomegaMatcher { .api }Matches HTTP response body. Expected can be string, bytes, or matcher.
Example:
Expect(resp).To(HaveHTTPBody(`{"status":"ok"}`))
Expect(resp).To(HaveHTTPBody(ContainSubstring("success")))
Expect(resp).To(HaveHTTPBody(MatchJSON(`{"status":"ok"}`)))func MatchJSON(json any) types.GomegaMatcher { .api }Checks JSON equality (ignoring whitespace and key order).
Example:
Expect(`{"foo":"bar"}`).To(MatchJSON(`{"foo": "bar"}`))
Expect(jsonBytes).To(MatchJSON(jsonString))func MatchXML(xml any) types.GomegaMatcher { .api }Checks XML equality (ignoring whitespace).
Example:
Expect(`<foo><bar>baz</bar></foo>`).To(MatchXML(`<foo> <bar>baz</bar> </foo>`))func MatchYAML(yaml any) types.GomegaMatcher { .api }Checks YAML equality.
Example:
Expect("foo: bar\n").To(MatchYAML("foo: bar"))func And(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }Combines matchers with logical AND. All must succeed. Fail-fast on first failure.
Example:
Expect("hi").To(And(HaveLen(2), Equal("hi")))
Expect(value).To(And(BeNumerically(">", 0), BeNumerically("<", 100)))func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }Combines matchers with logical OR. At least one must succeed. Returns on first success.
Example:
Expect("hi").To(Or(HaveLen(3), HaveLen(2)))
Expect(err).To(Or(BeNil(), MatchError("temporary")))func Not(matcher types.GomegaMatcher) types.GomegaMatcher { .api }Negates a matcher.
Example:
Expect(1).To(Not(Equal(2)))
Expect([]int{}).To(Not(ContainElement(1)))func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }Alias for And().
Example:
Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi")))func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }Alias for Or().
Example:
Expect("hi").Should(SatisfyAny(HaveLen(3), HaveLen(2)))func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { .api }Applies transformation function to value before matching. Transform must be a function taking one parameter and returning one value, or one value plus an error.
Example:
plus1 := func(i int) int { return i + 1 }
Expect(1).To(WithTransform(plus1, Equal(2)))
length := func(s string) int { return len(s) }
Expect("hello").To(WithTransform(length, Equal(5)))func Satisfy(predicate any) types.GomegaMatcher { .api }Uses custom predicate function. Function must return bool or (bool, error).
Example:
isEven := func(i int) bool { return i%2 == 0 }
Expect(2).To(Satisfy(isEven))
isPositive := func(i int) bool { return i > 0 }
Expect(5).To(Satisfy(isPositive))