or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-assertions.mdgbytes.mdgcustom.mdgexec.mdghttp.mdgleak.mdgmeasure.mdgstruct.mdindex.mdmatchers.mdtypes.md
tile.json

matchers.mddocs/

Gomega Matchers Reference

This document provides a comprehensive reference for all 70+ Gomega matchers. Matchers are the core of Gomega's assertion library, allowing you to express expectations about values in tests. Each matcher implements the types.GomegaMatcher interface and can be used with Expect().To(), Expect().ToNot(), Eventually().Should(), and other assertion methods.

Using Matchers

Matchers are used with Gomega's assertion functions:

Expect(actual).To(matcher)
Expect(actual).ToNot(matcher)
Eventually(func() string { return value }).Should(matcher)
Consistently(channel).ShouldNot(matcher)

All matcher functions return types.GomegaMatcher unless otherwise specified.

1. Equality Matchers

Matchers for comparing values for equality using different comparison strategies.

Equal

func Equal(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - The value to compare against

Returns: types.GomegaMatcher

Description: Succeeds if actual value is deeply equal to expected value using reflect.DeepEqual. This matcher is strict about types - both values must have the same type. If both values are nil, this matcher will error (use BeNil() instead).

Example:

Expect(5).To(Equal(5))
Expect("hello").To(Equal("hello"))
Expect([]int{1, 2, 3}).To(Equal([]int{1, 2, 3}))

BeEquivalentTo

func BeEquivalentTo(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - The value to compare against

Returns: types.GomegaMatcher

Description: Succeeds if actual value is equivalent to expected value. This matcher is more lenient than Equal() and allows equality between different numeric types or values that can be converted to the same type.

Example:

Expect(5).To(BeEquivalentTo(uint(5)))  // int vs uint
Expect(5.0).To(BeEquivalentTo(5))      // float64 vs int

BeComparableTo

func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { .api }

Parameters:

  • expected - The value to compare against
  • opts - Optional comparison options from github.com/google/go-cmp/cmp

Returns: types.GomegaMatcher

Description: Succeeds if actual value is deeply equal to expected value using gocmp.Equal from the go-cmp package. This allows for customizable deep comparison with options to ignore fields, transform values, etc.

Example:

import "github.com/google/go-cmp/cmp"

Expect(obj1).To(BeComparableTo(obj2, cmp.AllowUnexported(MyStruct{})))
Expect(timestamp1).To(BeComparableTo(timestamp2, cmpopts.EquateApproxTime(time.Second)))

BeIdenticalTo

func BeIdenticalTo(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - The value to compare against

Returns: types.GomegaMatcher

Description: Succeeds if actual value is identical to expected value using the == operator. This is stricter than Equal() and checks for pointer equality for reference types.

Example:

ptr := &MyStruct{}
Expect(ptr).To(BeIdenticalTo(ptr))
Expect("hello").To(BeIdenticalTo("hello"))

BeNil

func BeNil() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is nil. Works with pointers, slices, maps, channels, interfaces, and functions.

Example:

var ptr *int
Expect(ptr).To(BeNil())
Expect(err).To(BeNil())

BeZero

func BeZero() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is the zero value for its type (e.g., 0 for integers, "" for strings, nil for pointers, false for booleans).

Example:

Expect(0).To(BeZero())
Expect("").To(BeZero())
Expect(false).To(BeZero())

2. Boolean Matchers

Matchers specifically for boolean values.

BeTrue

func BeTrue() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is boolean true.

Example:

Expect(true).To(BeTrue())
Expect(isValid()).To(BeTrue())

BeFalse

func BeFalse() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is boolean false.

Example:

Expect(false).To(BeFalse())
Expect(isClosed()).To(BeFalse())

BeTrueBecause

func BeTrueBecause(format string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • format - Format string for custom reason message
  • args - Arguments for fmt.Sprintf formatting

Returns: types.GomegaMatcher

Description: Succeeds if actual value is boolean true. If the assertion fails (value is false), displays a custom reason message explaining why it should have been true.

Example:

Expect(user.IsAdmin()).To(BeTrueBecause("user %s should have admin privileges", user.Name))

BeFalseBecause

func BeFalseBecause(format string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • format - Format string for custom reason message
  • args - Arguments for fmt.Sprintf formatting

Returns: types.GomegaMatcher

Description: Succeeds if actual value is boolean false. If the assertion fails (value is true), displays a custom reason message explaining why it should have been false.

Example:

Expect(account.IsLocked()).To(BeFalseBecause("account %d should be accessible", account.ID))

3. Error Matchers

Matchers for working with Go error values.

HaveOccurred

func HaveOccurred() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is a non-nil error. Used to assert that an error was returned.

Example:

err := doSomethingRisky()
Expect(err).To(HaveOccurred())

Succeed

func Succeed() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual value is a nil error. This is the inverse of HaveOccurred() and is used to assert that no error occurred.

Example:

err := doSomething()
Expect(err).To(Succeed())
Expect(err).ToNot(HaveOccurred())  // equivalent

MatchError

func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { .api }

Parameters:

  • expected - Can be:
    • A string: matched against error.Error() output
    • An error value: matched using errors.Is() or reflect.DeepEqual
    • A matcher: applied to the error
    • A function func(error) bool: predicate to test the error
  • functionErrorDescription - Optional description used when expected is a function

Returns: types.GomegaMatcher

Description: Succeeds if actual is a non-nil error that matches the expected error. Provides flexible error matching strategies.

Example:

err := doSomething()
Expect(err).To(MatchError("connection failed"))
Expect(err).To(MatchError(io.EOF))
Expect(err).To(MatchError(ContainSubstring("timeout")))
Expect(err).To(MatchError(func(err error) bool {
    return errors.Is(err, context.Canceled)
}))

4. Numeric Matchers

Matchers for numeric comparisons and temporal values.

BeNumerically

func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { .api }

Parameters:

  • comparator - Comparison operator: "==", "!=", "<", "<=", ">", ">=", or "~" (approximately equal)
  • compareTo - One or two values:
    • For most operators: one value to compare against
    • For "~" operator: value and threshold

Returns: types.GomegaMatcher

Description: Performs numeric comparison on actual value. The "~" operator checks if the actual value is within the threshold of the comparison value.

Example:

Expect(5).To(BeNumerically("==", 5))
Expect(10).To(BeNumerically(">", 5))
Expect(3.14159).To(BeNumerically("~", 3.14, 0.01))  // within 0.01

BeTemporally

func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { .api }

Parameters:

  • comparator - Comparison operator: "==", "!=", "<", "<=", ">", ">=", or "~" (approximately equal)
  • compareTo - time.Time value to compare against
  • threshold - Optional threshold duration for "~" operator

Returns: types.GomegaMatcher

Description: Performs temporal comparison on time.Time values. The "~" operator checks if times are within the threshold duration of each other.

Example:

now := time.Now()
Expect(timestamp).To(BeTemporally(">", now.Add(-time.Hour)))
Expect(timestamp).To(BeTemporally("~", now, time.Second))

5. String Matchers

Matchers for string content and patterns.

ContainSubstring

func ContainSubstring(substr string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • substr - Substring to find (can contain fmt format specifiers)
  • args - Optional format arguments for fmt.Sprintf

Returns: types.GomegaMatcher

Description: Succeeds if actual string contains the specified substring.

Example:

Expect("hello world").To(ContainSubstring("world"))
Expect(message).To(ContainSubstring("error code %d", 404))

HavePrefix

func HavePrefix(prefix string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • prefix - Prefix to match (can contain fmt format specifiers)
  • args - Optional format arguments for fmt.Sprintf

Returns: types.GomegaMatcher

Description: Succeeds if actual string starts with the specified prefix.

Example:

Expect("hello world").To(HavePrefix("hello"))
Expect(filename).To(HavePrefix("test_"))

HaveSuffix

func HaveSuffix(suffix string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • suffix - Suffix to match (can contain fmt format specifiers)
  • args - Optional format arguments for fmt.Sprintf

Returns: types.GomegaMatcher

Description: Succeeds if actual string ends with the specified suffix.

Example:

Expect("hello world").To(HaveSuffix("world"))
Expect(filename).To(HaveSuffix(".txt"))

MatchRegexp

func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { .api }

Parameters:

  • regexp - Regular expression pattern
  • args - Optional format arguments for fmt.Sprintf

Returns: types.GomegaMatcher

Description: Succeeds if actual string matches the regular expression pattern.

Example:

Expect("hello123").To(MatchRegexp(`[a-z]+\d+`))
Expect(email).To(MatchRegexp(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`))

6. Collection Matchers

Matchers for arrays, slices, maps, channels, and other collections.

HaveLen

func HaveLen(count int) types.GomegaMatcher { .api }

Parameters:

  • count - Expected length

Returns: types.GomegaMatcher

Description: Succeeds if actual collection has the specified length. Works with arrays, slices, maps, channels, and strings.

Example:

Expect([]int{1, 2, 3}).To(HaveLen(3))
Expect("hello").To(HaveLen(5))
Expect(map[string]int{"a": 1, "b": 2}).To(HaveLen(2))

HaveCap

func HaveCap(count int) types.GomegaMatcher { .api }

Parameters:

  • count - Expected capacity

Returns: types.GomegaMatcher

Description: Succeeds if actual collection has the specified capacity. Works with slices and channels.

Example:

slice := make([]int, 3, 10)
Expect(slice).To(HaveCap(10))

BeEmpty

func BeEmpty() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual collection is empty (has length 0). Works with arrays, slices, maps, channels, and strings.

Example:

Expect([]int{}).To(BeEmpty())
Expect("").To(BeEmpty())
Expect(map[string]int{}).To(BeEmpty())

ContainElement

func ContainElement(element any, result ...any) types.GomegaMatcher { .api }

Parameters:

  • element - Element to find (can be a value or a matcher)
  • result - Optional pointer to store the matched element

Returns: types.GomegaMatcher

Description: Succeeds if actual collection contains at least one element matching the specified element. Works with arrays, slices, maps (checks values), and custom iterables.

Example:

Expect([]int{1, 2, 3}).To(ContainElement(2))
Expect([]string{"a", "b", "c"}).To(ContainElement(HavePrefix("b")))

var matched string
Expect([]string{"hello", "world"}).To(ContainElement(ContainSubstring("ell"), &matched))
// matched now contains "hello"

ContainElements

func ContainElements(elements ...any) types.GomegaMatcher { .api }

Parameters:

  • elements - Elements to find (can be values or matchers)

Returns: types.GomegaMatcher

Description: Succeeds if actual collection contains all specified elements. Order does not matter, and the collection can contain additional elements.

Example:

Expect([]int{1, 2, 3, 4}).To(ContainElements(2, 4))
Expect([]string{"a", "b", "c"}).To(ContainElements("c", "a"))

ConsistOf

func ConsistOf(elements ...any) types.GomegaMatcher { .api }

Parameters:

  • elements - Expected elements (can be values or matchers)

Returns: types.GomegaMatcher

Description: Succeeds if actual collection contains exactly the specified elements with no extras and no missing elements. Order does not matter.

Example:

Expect([]int{1, 2, 3}).To(ConsistOf(3, 1, 2))
Expect([]int{1, 2, 3}).To(ConsistOf(1, 2, 3))
Expect([]int{1, 2, 3}).ToNot(ConsistOf(1, 2))  // missing 3

HaveEach

func HaveEach(element any) types.GomegaMatcher { .api }

Parameters:

  • element - Matcher or value that every element must match

Returns: types.GomegaMatcher

Description: Succeeds if every element in the actual collection matches the specified element matcher or value.

Example:

Expect([]int{2, 4, 6, 8}).To(HaveEach(BeNumerically(">", 0)))
Expect([]string{"hello", "world"}).To(HaveEach(HaveLen(5)))

HaveExactElements

func HaveExactElements(elements ...any) types.GomegaMatcher { .api }

Parameters:

  • elements - Expected elements in exact order

Returns: types.GomegaMatcher

Description: Succeeds if actual collection contains exactly the specified elements in the exact order specified.

Example:

Expect([]int{1, 2, 3}).To(HaveExactElements(1, 2, 3))
Expect([]int{1, 2, 3}).ToNot(HaveExactElements(3, 2, 1))  // wrong order

7. Map Matchers

Matchers specifically for map operations.

HaveKey

func HaveKey(key any) types.GomegaMatcher { .api }

Parameters:

  • key - Key to find (can be a value or a matcher)

Returns: types.GomegaMatcher

Description: Succeeds if actual map contains the specified key.

Example:

Expect(map[string]int{"a": 1, "b": 2}).To(HaveKey("a"))
Expect(map[int]string{1: "one", 2: "two"}).To(HaveKey(BeNumerically(">", 0)))

HaveKeyWithValue

func HaveKeyWithValue(key any, value any) types.GomegaMatcher { .api }

Parameters:

  • key - Key to find (can be a value or a matcher)
  • value - Value to match (can be a value or a matcher)

Returns: types.GomegaMatcher

Description: Succeeds if actual map contains the specified key with a value matching the specified value.

Example:

Expect(map[string]int{"a": 1, "b": 2}).To(HaveKeyWithValue("a", 1))
Expect(config).To(HaveKeyWithValue("timeout", BeNumerically(">", 0)))

HaveValue

func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • matcher - Matcher to apply to dereferenced value

Returns: types.GomegaMatcher

Description: Succeeds if the dereferenced pointer value matches the specified matcher. This is useful for asserting on pointer values.

Example:

value := 42
ptr := &value
Expect(ptr).To(HaveValue(Equal(42)))

BeKeyOf

func BeKeyOf(element any) types.GomegaMatcher { .api }

Parameters:

  • element - Map or struct to check

Returns: types.GomegaMatcher

Description: Succeeds if actual value is a key in the specified map.

Example:

myMap := map[string]int{"a": 1, "b": 2}
Expect("a").To(BeKeyOf(myMap))
Expect("c").ToNot(BeKeyOf(myMap))

8. Channel Matchers

Matchers for channel operations.

BeClosed

func BeClosed() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual channel is closed. This matcher attempts to receive from the channel to detect if it's closed.

Example:

ch := make(chan int)
close(ch)
Expect(ch).To(BeClosed())

Receive

func Receive(args ...any) types.GomegaMatcher { .api }

Parameters:

  • args - Optional arguments:
    • A matcher to apply to received value
    • A pointer to store the received value

Returns: types.GomegaMatcher

Description: Succeeds if a value can be received from the channel. This matcher never blocks - it uses a select statement to detect if a value is available. Can optionally apply a matcher to the received value or capture it.

Example:

ch := make(chan int, 1)
ch <- 42
Expect(ch).To(Receive())

// With matcher
Expect(ch).To(Receive(Equal(42)))

// Capture value
var received int
Eventually(ch).Should(Receive(&received))

BeSent

func BeSent(arg any) types.GomegaMatcher { .api }

Parameters:

  • arg - Value to send to the channel

Returns: types.GomegaMatcher

Description: Succeeds if the specified value can be sent to the channel. This matcher never blocks - it uses a select statement to detect if the channel can accept a value.

Example:

ch := make(chan int, 1)
Expect(ch).To(BeSent(42))

9. Type Matchers

Matchers for type checking and type relationships.

BeAssignableToTypeOf

func BeAssignableToTypeOf(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - Value whose type to check against

Returns: types.GomegaMatcher

Description: Succeeds if actual value's type is assignable to the type of the expected value according to Go's type system.

Example:

var reader io.Reader
Expect(&bytes.Buffer{}).To(BeAssignableToTypeOf(reader))

var num int
Expect(5).To(BeAssignableToTypeOf(num))

BeElementOf

func BeElementOf(elements ...any) types.GomegaMatcher { .api }

Parameters:

  • elements - Collection of possible values

Returns: types.GomegaMatcher

Description: Succeeds if actual value is equal to one of the specified elements. Similar to checking if a value is in a set.

Example:

Expect("blue").To(BeElementOf("red", "green", "blue"))
Expect(status).To(BeElementOf(http.StatusOK, http.StatusCreated, http.StatusAccepted))

10. Function/Panic Matchers

Matchers for testing function behavior and panics.

Panic

func Panic() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual function panics when called. The actual value must be a function with no parameters.

Example:

Expect(func() {
    panic("oh no!")
}).To(Panic())

badFunc := func() { panic("error") }
Expect(badFunc).To(Panic())

PanicWith

func PanicWith(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - Value or matcher for the panic value

Returns: types.GomegaMatcher

Description: Succeeds if actual function panics with a value matching the expected value or matcher. The actual value must be a function with no parameters.

Example:

Expect(func() {
    panic("specific error")
}).To(PanicWith("specific error"))

Expect(func() {
    panic(fmt.Errorf("error occurred"))
}).To(PanicWith(MatchError(ContainSubstring("occurred"))))

11. File System Matchers

Matchers for file system operations and file existence checks.

BeAnExistingFile

func BeAnExistingFile() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual path string points to an existing file or directory in the file system.

Example:

Expect("/tmp/myfile.txt").To(BeAnExistingFile())
Expect(filepath.Join(tempDir, "config.json")).To(BeAnExistingFile())

BeARegularFile

func BeARegularFile() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual path string points to a regular file (not a directory or special file).

Example:

Expect("/etc/hosts").To(BeARegularFile())
Expect("/tmp").ToNot(BeARegularFile())  // it's a directory

BeADirectory

func BeADirectory() types.GomegaMatcher { .api }

Returns: types.GomegaMatcher

Description: Succeeds if actual path string points to a directory.

Example:

Expect("/tmp").To(BeADirectory())
Expect("/etc/hosts").ToNot(BeADirectory())  // it's a file

12. HTTP Matchers

Matchers for HTTP responses and requests.

HaveHTTPStatus

func HaveHTTPStatus(expected ...any) types.GomegaMatcher { .api }

Parameters:

  • expected - One or more HTTP status codes (integers) or status names (strings)

Returns: types.GomegaMatcher

Description: Succeeds if the HTTP response has one of the expected status codes. Works with *http.Response or *httptest.ResponseRecorder.

Example:

resp, _ := http.Get("http://example.com")
Expect(resp).To(HaveHTTPStatus(http.StatusOK))
Expect(resp).To(HaveHTTPStatus(200))
Expect(resp).To(HaveHTTPStatus("OK"))
Expect(resp).To(HaveHTTPStatus(http.StatusOK, http.StatusCreated))

HaveHTTPHeaderWithValue

func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher { .api }

Parameters:

  • header - Header name (case-insensitive)
  • value - Expected header value (string or matcher)

Returns: types.GomegaMatcher

Description: Succeeds if the HTTP response has the specified header with a value matching the expected value.

Example:

Expect(resp).To(HaveHTTPHeaderWithValue("Content-Type", "application/json"))
Expect(resp).To(HaveHTTPHeaderWithValue("Content-Type", ContainSubstring("json")))

HaveHTTPBody

func HaveHTTPBody(expected any) types.GomegaMatcher { .api }

Parameters:

  • expected - Expected body content (string, []byte, or matcher)

Returns: types.GomegaMatcher

Description: Succeeds if the HTTP response body matches the expected content. The response body is read and can be matched against a string, byte slice, or any matcher.

Example:

Expect(resp).To(HaveHTTPBody(ContainSubstring("success")))
Expect(resp).To(HaveHTTPBody(MatchJSON(`{"status": "ok"}`)))
Expect(resp).To(HaveHTTPBody([]byte("plain text")))

13. Data Format Matchers

Matchers for structured data formats like JSON, XML, and YAML.

MatchJSON

func MatchJSON(json any) types.GomegaMatcher { .api }

Parameters:

  • json - Expected JSON content (string, []byte, or object to marshal)

Returns: types.GomegaMatcher

Description: Succeeds if actual value is semantically equivalent JSON to the expected JSON. This performs a deep comparison of the JSON structures, ignoring whitespace and key ordering.

Example:

Expect(`{"name": "John", "age": 30}`).To(MatchJSON(`{"age": 30, "name": "John"}`))

// Can also compare against an object
expected := map[string]interface{}{"name": "John", "age": 30}
Expect(jsonString).To(MatchJSON(expected))

MatchXML

func MatchXML(xml any) types.GomegaMatcher { .api }

Parameters:

  • xml - Expected XML content (string or []byte)

Returns: types.GomegaMatcher

Description: Succeeds if actual value is semantically equivalent XML to the expected XML. Compares XML structures ignoring whitespace and attribute ordering.

Example:

Expect(`<person><name>John</name></person>`).To(MatchXML(`<person><name>John</name></person>`))

MatchYAML

func MatchYAML(yaml any) types.GomegaMatcher { .api }

Parameters:

  • yaml - Expected YAML content (string, []byte, or object to marshal)

Returns: types.GomegaMatcher

Description: Succeeds if actual value is semantically equivalent YAML to the expected YAML. Compares YAML structures ignoring formatting differences.

Example:

Expect("name: John\nage: 30").To(MatchYAML("age: 30\nname: John"))

// Can also compare against an object
expected := map[string]interface{}{"name": "John", "age": 30}
Expect(yamlString).To(MatchYAML(expected))

14. Struct/Field Matchers

Matchers for accessing and validating struct fields.

HaveField

func HaveField(field string, expected any) types.GomegaMatcher { .api }

Parameters:

  • field - Field name (supports nested fields using dot notation like "Parent.Child")
  • expected - Expected value or matcher for the field

Returns: types.GomegaMatcher

Description: Succeeds if the struct has the specified field with a value matching the expected value or matcher. Supports nested field access and works with both exported and unexported fields.

Example:

type Person struct {
    Name string
    Age  int
    Address struct {
        City string
    }
}

person := Person{Name: "John", Age: 30}
Expect(person).To(HaveField("Name", "John"))
Expect(person).To(HaveField("Age", BeNumerically(">", 18)))
Expect(person).To(HaveField("Address.City", "NYC"))

HaveExistingField

func HaveExistingField(field string) types.GomegaMatcher { .api }

Parameters:

  • field - Field name to check for existence

Returns: types.GomegaMatcher

Description: Succeeds if the struct has the specified field, regardless of its value.

Example:

type Config struct {
    Timeout int
    Host    string
}

cfg := Config{}
Expect(cfg).To(HaveExistingField("Timeout"))
Expect(cfg).To(HaveExistingField("Host"))
Expect(cfg).ToNot(HaveExistingField("Port"))

15. Predicate/Transform Matchers

Matchers that use custom functions or transformations.

Satisfy

func Satisfy(predicate any) types.GomegaMatcher { .api }

Parameters:

  • predicate - Function of type func(T) bool where T is the type of the actual value

Returns: types.GomegaMatcher

Description: Succeeds if the predicate function returns true when called with the actual value. Allows custom validation logic.

Example:

isEven := func(n int) bool { return n%2 == 0 }
Expect(4).To(Satisfy(isEven))

isValidEmail := func(s string) bool {
    return strings.Contains(s, "@")
}
Expect("user@example.com").To(Satisfy(isValidEmail))

WithTransform

func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • transform - Function of type func(T) U that transforms the actual value
  • matcher - Matcher to apply to the transformed value

Returns: types.GomegaMatcher

Description: Transforms the actual value using the transform function, then applies the matcher to the result. Useful for extracting or converting values before matching.

Example:

// Transform string to its length, then check the length
Expect("hello").To(WithTransform(func(s string) int {
    return len(s)
}, Equal(5)))

// Extract field and match it
type Person struct { Age int }
Expect(Person{Age: 25}).To(WithTransform(func(p Person) int {
    return p.Age
}, BeNumerically(">", 18)))

16. Composite Matchers

Matchers that combine or modify other matchers.

And

func And(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • ms - Variable number of matchers to combine with logical AND

Returns: types.GomegaMatcher

Description: Succeeds if ALL of the provided matchers succeed. This performs a logical AND operation on multiple matchers.

Example:

Expect("hello world").To(And(
    ContainSubstring("hello"),
    ContainSubstring("world"),
    HaveLen(11),
))

Expect(42).To(And(
    BeNumerically(">", 0),
    BeNumerically("<", 100),
))

Or

func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • ms - Variable number of matchers to combine with logical OR

Returns: types.GomegaMatcher

Description: Succeeds if ANY of the provided matchers succeed. This performs a logical OR operation on multiple matchers.

Example:

Expect(status).To(Or(
    Equal(http.StatusOK),
    Equal(http.StatusCreated),
    Equal(http.StatusAccepted),
))

Expect("test@example.com").To(Or(
    HaveSuffix(".com"),
    HaveSuffix(".org"),
))

Not

func Not(matcher types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • matcher - Matcher to negate

Returns: types.GomegaMatcher

Description: Negates the provided matcher. Succeeds if the matcher fails, and fails if the matcher succeeds. This is equivalent to using .ToNot() or .ShouldNot().

Example:

Expect(value).To(Not(BeNil()))
// Equivalent to: Expect(value).ToNot(BeNil())

Expect(slice).To(Not(BeEmpty()))

SatisfyAll

func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • matchers - Variable number of matchers

Returns: types.GomegaMatcher

Description: Alias for And(). Succeeds if ALL matchers succeed.

Example:

Expect(user).To(SatisfyAll(
    HaveField("Name", Not(BeEmpty())),
    HaveField("Age", BeNumerically(">", 0)),
    HaveField("Email", MatchRegexp(`.*@.*`)),
))

SatisfyAny

func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • matchers - Variable number of matchers

Returns: types.GomegaMatcher

Description: Alias for Or(). Succeeds if ANY matcher succeeds.

Example:

Expect(value).To(SatisfyAny(
    BeNil(),
    Equal(0),
    Equal(""),
))

Matcher Composition Examples

Matchers can be composed together to create complex assertions:

// Combining multiple matchers
Expect(users).To(And(
    HaveLen(BeNumerically(">", 0)),
    ContainElement(HaveField("Role", "admin")),
))

// Nested transformations
Expect(response).To(WithTransform(func(r *http.Response) int {
    return r.StatusCode
}, Or(Equal(200), Equal(201))))

// Complex struct matching
Expect(config).To(And(
    HaveField("Database.Host", Not(BeEmpty())),
    HaveField("Database.Port", BeNumerically(">", 0)),
    HaveField("Timeout", BeNumerically(">=", 30*time.Second)),
))

// Collection element matching
Expect(orders).To(ContainElement(And(
    HaveField("Status", "pending"),
    HaveField("Amount", BeNumerically(">", 100)),
)))

Using Matchers with Eventually and Consistently

All matchers work seamlessly with asynchronous assertions:

// Eventually with matcher
Eventually(func() []string {
    return getActiveUsers()
}).Should(ContainElement("admin"))

// Consistently with matcher
Consistently(func() int {
    return counter.Value()
}).Should(BeNumerically(">=", 0))

// Complex async matching
Eventually(func() *Config {
    return loadConfig()
}).Should(And(
    Not(BeNil()),
    HaveField("Initialized", BeTrue()),
))

17. Advanced Struct Matchers (gstruct package)

The github.com/onsi/gomega/gstruct package provides advanced matchers for complex struct and collection matching scenarios.

MatchAllFields

func MatchAllFields(fields Fields) types.GomegaMatcher { .api }

Parameters:

  • fields - Map of field names to matchers (gstruct.Fields)

Returns: types.GomegaMatcher

Description: Succeeds if ALL struct fields match the provided matchers and there are no extra fields. This is strict matching that requires every field to be specified.

Example:

import "github.com/onsi/gomega/gstruct"

type Person struct {
    Name string
    Age  int
}

Expect(person).To(gstruct.MatchAllFields(gstruct.Fields{
    "Name": Equal("John"),
    "Age":  BeNumerically(">", 18),
}))

MatchFields

func MatchFields(options FieldsOptions, fields Fields) types.GomegaMatcher { .api }

Parameters:

  • options - Matching options: gstruct.IgnoreExtras or gstruct.IgnoreMissing
  • fields - Map of field names to matchers

Returns: types.GomegaMatcher

Description: Succeeds if specified struct fields match. Options control whether extra fields or missing specifications are allowed.

Example:

import "github.com/onsi/gomega/gstruct"

Expect(person).To(gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{
    "Name": Equal("John"),
    // Other fields are ignored
}))

MatchAllKeys

func MatchAllKeys(keys Keys) types.GomegaMatcher { .api }

Parameters:

  • keys - Map of keys to value matchers (gstruct.Keys)

Returns: types.GomegaMatcher

Description: Succeeds if ALL map keys match the provided matchers and there are no extra keys.

Example:

import "github.com/onsi/gomega/gstruct"

myMap := map[string]int{"a": 1, "b": 2}
Expect(myMap).To(gstruct.MatchAllKeys(gstruct.Keys{
    "a": Equal(1),
    "b": Equal(2),
}))

MatchKeys

func MatchKeys(options KeysOptions, keys Keys) types.GomegaMatcher { .api }

Parameters:

  • options - Matching options: gstruct.IgnoreExtras or gstruct.IgnoreMissing
  • keys - Map of keys to value matchers

Returns: types.GomegaMatcher

Description: Succeeds if specified map keys match. Options control whether extra keys or missing specifications are allowed.

Example:

import "github.com/onsi/gomega/gstruct"

Expect(myMap).To(gstruct.MatchKeys(gstruct.IgnoreExtras, gstruct.Keys{
    "a": Equal(1),
}))

MatchAllElements

func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher { .api }

Parameters:

  • identifier - Function of type func(element any) string to generate identifier for each element
  • elements - Map of identifiers to matchers (gstruct.Elements)

Returns: types.GomegaMatcher

Description: Succeeds if ALL slice/array elements match by identity and there are no extra elements. Uses the identifier function to map elements to matcher specifications.

Example:

import "github.com/onsi/gomega/gstruct"

type User struct {
    ID   string
    Name string
}

users := []User{
    {ID: "1", Name: "Alice"},
    {ID: "2", Name: "Bob"},
}

Expect(users).To(gstruct.MatchAllElements(
    func(element interface{}) string {
        return element.(User).ID
    },
    gstruct.Elements{
        "1": gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{"Name": Equal("Alice")}),
        "2": gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{"Name": Equal("Bob")}),
    },
))

MatchElements

func MatchElements(identifier Identifier, options ElementsOptions, elements Elements) types.GomegaMatcher { .api }

Parameters:

  • identifier - Function to generate identifier for each element
  • options - Matching options: gstruct.IgnoreExtras, gstruct.IgnoreMissing, or gstruct.AllowDuplicates
  • elements - Map of identifiers to matchers

Returns: types.GomegaMatcher

Description: Succeeds if specified slice/array elements match by identity. Options control whether extra elements, missing specifications, or duplicate identifiers are allowed.

Example:

import "github.com/onsi/gomega/gstruct"

Expect(users).To(gstruct.MatchElements(
    func(element interface{}) string {
        return element.(User).ID
    },
    gstruct.IgnoreExtras,
    gstruct.Elements{
        "1": gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{"Name": Equal("Alice")}),
    },
))

PointTo

func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { .api }

Parameters:

  • matcher - Matcher to apply to the dereferenced value

Returns: types.GomegaMatcher

Description: Dereferences a pointer and applies the matcher to the pointed-to value. Fails if the pointer is nil.

Example:

import "github.com/onsi/gomega/gstruct"

value := 42
ptr := &value
Expect(ptr).To(gstruct.PointTo(Equal(42)))

type Config struct { Port int }
cfg := &Config{Port: 8080}
Expect(cfg).To(gstruct.PointTo(gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{
    "Port": Equal(8080),
})))

18. Byte Buffer Matchers (gbytes package)

The github.com/onsi/gomega/gbytes package provides matchers for testing byte streams and buffers.

Say

func Say(expected any, args ...any) types.GomegaMatcher { .api }

Parameters:

  • expected - String pattern, regular expression, or matcher
  • args - Optional format arguments for fmt.Sprintf

Returns: types.GomegaMatcher

Description: Succeeds if the buffer (or io.Reader) eventually contains content matching the expected pattern. This matcher is designed to work with *gbytes.Buffer and can match string patterns or regular expressions.

Example:

import "github.com/onsi/gomega/gbytes"

buffer := gbytes.NewBuffer()
buffer.Write([]byte("Hello, World!"))

Expect(buffer).To(gbytes.Say("World"))
Expect(buffer).To(gbytes.Say("Hello.*World"))  // regex

19. Process Matchers (gexec package)

The github.com/onsi/gomega/gexec package provides matchers for testing external processes.

Exit

func Exit(optionalExitCode ...int) types.GomegaMatcher { .api }

Parameters:

  • optionalExitCode - Optional expected exit code(s). If not provided, matches any exit.

Returns: types.GomegaMatcher

Description: Succeeds when a *gexec.Session has exited. Optionally verifies the exit code matches one of the expected codes.

Example:

import (
    "os/exec"
    "github.com/onsi/gomega/gexec"
)

command := exec.Command("echo", "hello")
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ToNot(HaveOccurred())

Eventually(session).Should(gexec.Exit(0))  // wait for exit with code 0
Eventually(session).Should(gexec.Exit())   // wait for any exit

20. Goroutine Leak Matchers (gleak package)

The github.com/onsi/gomega/gleak package provides matchers for detecting goroutine leaks in tests.

HaveLeaked

func HaveLeaked(options ...IgnoredGoroutines) types.GomegaMatcher { .api }

Parameters:

  • options - Optional goroutine filters to ignore (e.g., gleak.IgnoreCurrent(), gleak.IgnoreBackgroundGoroutines())

Returns: types.GomegaMatcher

Description: Fails if goroutines have leaked since the options were captured. Used to detect goroutine leaks in tests by comparing current goroutines against a baseline.

Example:

import "github.com/onsi/gomega/gleak"

// Capture current goroutines at start of test
good := gleak.IgnoreCurrent()

// Run test code that should not leak goroutines
startWorker()

// Check for leaks
Eventually(gleak.Goroutines).ShouldNot(gleak.HaveLeaked(good))

Matcher Count Summary

This document covers 70+ matchers across all Gomega packages:

  • Equality Matchers: 6 matchers (Equal, BeEquivalentTo, BeComparableTo, BeIdenticalTo, BeNil, BeZero)
  • Boolean Matchers: 4 matchers (BeTrue, BeFalse, BeTrueBecause, BeFalseBecause)
  • Error Matchers: 3 matchers (HaveOccurred, Succeed, MatchError)
  • Numeric Matchers: 2 matchers (BeNumerically, BeTemporally)
  • String Matchers: 4 matchers (ContainSubstring, HavePrefix, HaveSuffix, MatchRegexp)
  • Collection Matchers: 8 matchers (HaveLen, HaveCap, BeEmpty, ContainElement, ContainElements, ConsistOf, HaveEach, HaveExactElements)
  • Map Matchers: 4 matchers (HaveKey, HaveKeyWithValue, HaveValue, BeKeyOf)
  • Channel Matchers: 3 matchers (BeClosed, Receive, BeSent)
  • Type Matchers: 2 matchers (BeAssignableToTypeOf, BeElementOf)
  • Function/Panic Matchers: 2 matchers (Panic, PanicWith)
  • File System Matchers: 3 matchers (BeAnExistingFile, BeARegularFile, BeADirectory)
  • HTTP Matchers: 3 matchers (HaveHTTPStatus, HaveHTTPHeaderWithValue, HaveHTTPBody)
  • Data Format Matchers: 3 matchers (MatchJSON, MatchXML, MatchYAML)
  • Struct/Field Matchers: 2 matchers (HaveField, HaveExistingField)
  • Predicate/Transform Matchers: 2 matchers (Satisfy, WithTransform)
  • Composite Matchers: 5 matchers (And, Or, Not, SatisfyAll, SatisfyAny)
  • Advanced Struct Matchers (gstruct): 7 matchers (MatchAllFields, MatchFields, MatchAllKeys, MatchKeys, MatchAllElements, MatchElements, PointTo)
  • Byte Buffer Matchers (gbytes): 1 matcher (Say)
  • Process Matchers (gexec): 1 matcher (Exit)
  • Goroutine Leak Matchers (gleak): 1 matcher (HaveLeaked)

Total: 66 documented matchers

Custom Matcher Tips

While Gomega provides 70+ matchers, you can create custom matchers for domain-specific assertions:

  1. Use Satisfy() for simple custom predicates
  2. Use WithTransform() to extract values before matching
  3. Use composite matchers (And, Or) to combine existing matchers
  4. For reusable custom matchers, use the gcustom package
  5. Use gstruct matchers for complex nested structure validation
// Simple predicate
isValidUUID := func(s string) bool {
    _, err := uuid.Parse(s)
    return err == nil
}
Expect(id).To(Satisfy(isValidUUID))

// Transform and match
Expect(obj).To(WithTransform(extractID, MatchRegexp(`^[0-9a-f]+$`)))

// Complex struct matching with gstruct
import "github.com/onsi/gomega/gstruct"
Expect(response).To(gstruct.PointTo(gstruct.MatchFields(gstruct.IgnoreExtras, gstruct.Fields{
    "Status": Equal("success"),
    "Data":   Not(BeNil()),
})))

This comprehensive reference covers all 70+ Gomega matchers organized by category. Each matcher is documented with its signature, parameters, return type, description, and practical examples to help you write expressive and maintainable tests.