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.
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.
Matchers for comparing values for equality using different comparison strategies.
func Equal(expected any) types.GomegaMatcher { .api }Parameters:
expected - The value to compare againstReturns: 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}))func BeEquivalentTo(expected any) types.GomegaMatcher { .api }Parameters:
expected - The value to compare againstReturns: 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 intfunc BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { .api }Parameters:
expected - The value to compare againstopts - Optional comparison options from github.com/google/go-cmp/cmpReturns: 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)))func BeIdenticalTo(expected any) types.GomegaMatcher { .api }Parameters:
expected - The value to compare againstReturns: 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"))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())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())Matchers specifically for boolean values.
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())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())func BeTrueBecause(format string, args ...any) types.GomegaMatcher { .api }Parameters:
format - Format string for custom reason messageargs - Arguments for fmt.Sprintf formattingReturns: 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))func BeFalseBecause(format string, args ...any) types.GomegaMatcher { .api }Parameters:
format - Format string for custom reason messageargs - Arguments for fmt.Sprintf formattingReturns: 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))Matchers for working with Go error values.
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())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()) // equivalentfunc MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { .api }Parameters:
expected - Can be:
error.Error() outputerrors.Is() or reflect.DeepEqualfunc(error) bool: predicate to test the errorfunctionErrorDescription - Optional description used when expected is a functionReturns: 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)
}))Matchers for numeric comparisons and temporal values.
func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { .api }Parameters:
comparator - Comparison operator: "==", "!=", "<", "<=", ">", ">=", or "~" (approximately equal)compareTo - One or two values:
"~" operator: value and thresholdReturns: 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.01func 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 againstthreshold - Optional threshold duration for "~" operatorReturns: 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))Matchers for string content and patterns.
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.SprintfReturns: 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))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.SprintfReturns: types.GomegaMatcher
Description: Succeeds if actual string starts with the specified prefix.
Example:
Expect("hello world").To(HavePrefix("hello"))
Expect(filename).To(HavePrefix("test_"))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.SprintfReturns: types.GomegaMatcher
Description: Succeeds if actual string ends with the specified suffix.
Example:
Expect("hello world").To(HaveSuffix("world"))
Expect(filename).To(HaveSuffix(".txt"))func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { .api }Parameters:
regexp - Regular expression patternargs - Optional format arguments for fmt.SprintfReturns: 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,}$`))Matchers for arrays, slices, maps, channels, and other collections.
func HaveLen(count int) types.GomegaMatcher { .api }Parameters:
count - Expected lengthReturns: 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))func HaveCap(count int) types.GomegaMatcher { .api }Parameters:
count - Expected capacityReturns: 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))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())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 elementReturns: 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"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"))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 3func HaveEach(element any) types.GomegaMatcher { .api }Parameters:
element - Matcher or value that every element must matchReturns: 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)))func HaveExactElements(elements ...any) types.GomegaMatcher { .api }Parameters:
elements - Expected elements in exact orderReturns: 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 orderMatchers specifically for map operations.
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)))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)))func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
matcher - Matcher to apply to dereferenced valueReturns: 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)))func BeKeyOf(element any) types.GomegaMatcher { .api }Parameters:
element - Map or struct to checkReturns: 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))Matchers for channel operations.
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())func Receive(args ...any) types.GomegaMatcher { .api }Parameters:
args - Optional arguments:
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))func BeSent(arg any) types.GomegaMatcher { .api }Parameters:
arg - Value to send to the channelReturns: 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))Matchers for type checking and type relationships.
func BeAssignableToTypeOf(expected any) types.GomegaMatcher { .api }Parameters:
expected - Value whose type to check againstReturns: 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))func BeElementOf(elements ...any) types.GomegaMatcher { .api }Parameters:
elements - Collection of possible valuesReturns: 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))Matchers for testing function behavior and panics.
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())func PanicWith(expected any) types.GomegaMatcher { .api }Parameters:
expected - Value or matcher for the panic valueReturns: 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"))))Matchers for file system operations and file existence checks.
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())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 directoryfunc 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 fileMatchers for HTTP responses and requests.
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))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")))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")))Matchers for structured data formats like JSON, XML, and YAML.
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))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>`))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))Matchers for accessing and validating struct fields.
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 fieldReturns: 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"))func HaveExistingField(field string) types.GomegaMatcher { .api }Parameters:
field - Field name to check for existenceReturns: 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"))Matchers that use custom functions or transformations.
func Satisfy(predicate any) types.GomegaMatcher { .api }Parameters:
predicate - Function of type func(T) bool where T is the type of the actual valueReturns: 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))func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
transform - Function of type func(T) U that transforms the actual valuematcher - Matcher to apply to the transformed valueReturns: 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)))Matchers that combine or modify other matchers.
func And(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
ms - Variable number of matchers to combine with logical ANDReturns: 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),
))func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
ms - Variable number of matchers to combine with logical ORReturns: 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"),
))func Not(matcher types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
matcher - Matcher to negateReturns: 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()))func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
matchers - Variable number of matchersReturns: 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(`.*@.*`)),
))func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
matchers - Variable number of matchersReturns: types.GomegaMatcher
Description: Alias for Or(). Succeeds if ANY matcher succeeds.
Example:
Expect(value).To(SatisfyAny(
BeNil(),
Equal(0),
Equal(""),
))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)),
)))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()),
))The github.com/onsi/gomega/gstruct package provides advanced matchers for complex struct and collection matching scenarios.
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),
}))func MatchFields(options FieldsOptions, fields Fields) types.GomegaMatcher { .api }Parameters:
options - Matching options: gstruct.IgnoreExtras or gstruct.IgnoreMissingfields - Map of field names to matchersReturns: 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
}))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),
}))func MatchKeys(options KeysOptions, keys Keys) types.GomegaMatcher { .api }Parameters:
options - Matching options: gstruct.IgnoreExtras or gstruct.IgnoreMissingkeys - Map of keys to value matchersReturns: 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),
}))func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher { .api }Parameters:
identifier - Function of type func(element any) string to generate identifier for each elementelements - 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")}),
},
))func MatchElements(identifier Identifier, options ElementsOptions, elements Elements) types.GomegaMatcher { .api }Parameters:
identifier - Function to generate identifier for each elementoptions - Matching options: gstruct.IgnoreExtras, gstruct.IgnoreMissing, or gstruct.AllowDuplicateselements - Map of identifiers to matchersReturns: 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")}),
},
))func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { .api }Parameters:
matcher - Matcher to apply to the dereferenced valueReturns: 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),
})))The github.com/onsi/gomega/gbytes package provides matchers for testing byte streams and buffers.
func Say(expected any, args ...any) types.GomegaMatcher { .api }Parameters:
expected - String pattern, regular expression, or matcherargs - Optional format arguments for fmt.SprintfReturns: 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")) // regexThe github.com/onsi/gomega/gexec package provides matchers for testing external processes.
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 exitThe github.com/onsi/gomega/gleak package provides matchers for detecting goroutine leaks in tests.
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))This document covers 70+ matchers across all Gomega packages:
Total: 66 documented matchers
While Gomega provides 70+ matchers, you can create custom matchers for domain-specific assertions:
Satisfy() for simple custom predicatesWithTransform() to extract values before matchingAnd, Or) to combine existing matchersgcustom packagegstruct 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.