This document comprehensively covers Gomega's core assertion APIs including setup, synchronous assertions, asynchronous assertions, polling control, and utility functions.
import "github.com/onsi/gomega"For type references:
import "github.com/onsi/gomega/types"func RegisterFailHandler(fail types.GomegaFailHandler) { .api }Connects Gomega to a test framework (typically Ginkgo). Sets the package-level fail handler that will be called when assertions fail.
Parameters:
fail types.GomegaFailHandler - Function with signature func(message string, callerSkip ...int)Usage:
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = BeforeSuite(func() {
RegisterFailHandler(Fail) // Connects to Ginkgo
})func RegisterTestingT(t types.GomegaTestingT) { .api }Deprecated: Use NewWithT() instead.
Registers Gomega with Go's *testing.T for use in standard Go tests.
Parameters:
t types.GomegaTestingT - Interface satisfied by *testing.T with methods Helper() and Fatalf(format string, args ...any)func NewGomega(fail types.GomegaFailHandler) Gomega { .api }Creates a new Gomega instance with a custom fail handler for isolated testing contexts. Useful when you want to use Gomega's matchers without causing a test to fail, or for managing multiple independent Gomega contexts.
Parameters:
fail types.GomegaFailHandler - Custom fail handler functionReturns:
Gomega - New Gomega instanceUsage:
// Create isolated Gomega for capturing failures
customGomega := NewGomega(func(message string, callerSkip ...int) {
// Custom failure handling
fmt.Println("Assertion failed:", message)
})
customGomega.Expect(value).To(Equal(expected))func NewWithT(t types.GomegaTestingT) *WithT { .api }Creates a Gomega instance bound to *testing.T for use in standard Go tests. This is the recommended way to use Gomega with Go's testing package.
Parameters:
t types.GomegaTestingT - Usually *testing.TReturns:
*WithT - Gomega instance bound to the testUsage:
func TestMyFunction(t *testing.T) {
g := NewWithT(t)
result := MyFunction()
g.Expect(result).To(Equal(42))
}func SetDefaultEventuallyTimeout(t time.Duration) { .api }Sets the default timeout duration for Eventually assertions. Eventually will repeatedly poll your condition until it succeeds or this timeout elapses.
Parameters:
t time.Duration - Timeout duration (default: 1 second)Usage:
SetDefaultEventuallyTimeout(5 * time.Second)func SetDefaultEventuallyPollingInterval(t time.Duration) { .api }Sets the default polling interval for Eventually assertions. This determines how frequently the condition is checked.
Parameters:
t time.Duration - Polling interval (default: 10 milliseconds)Usage:
SetDefaultEventuallyPollingInterval(100 * time.Millisecond)func SetDefaultConsistentlyDuration(t time.Duration) { .api }Sets the default duration for Consistently assertions. Consistently will verify that your condition is satisfied for this long.
Parameters:
t time.Duration - Duration (default: 100 milliseconds)Usage:
SetDefaultConsistentlyDuration(500 * time.Millisecond)func SetDefaultConsistentlyPollingInterval(t time.Duration) { .api }Sets the default polling interval for Consistently assertions.
Parameters:
t time.Duration - Polling interval (default: 10 milliseconds)Usage:
SetDefaultConsistentlyPollingInterval(50 * time.Millisecond)func EnforceDefaultTimeoutsWhenUsingContexts() { .api }Forces Eventually and Consistently to apply default timeouts even when a context.Context is provided. By default, when a context is provided without an explicit timeout, Gomega relies solely on the context's cancellation.
Usage:
EnforceDefaultTimeoutsWhenUsingContexts()
// Now all Eventually calls with context will use default timeouts
Eventually(ctx, func() bool {
return checkCondition()
}).Should(BeTrue()) // Will timeout after default Eventually timeoutfunc DisableDefaultTimeoutsWhenUsingContext() { .api }Disables default timeouts when context.Context is provided to Eventually or Consistently. This is the default behavior - the assertion will only stop when the context is cancelled.
Usage:
DisableDefaultTimeoutsWhenUsingContext()Synchronous assertions check a condition immediately and fail if the condition is not met.
func Expect(actual any, extra ...any) Assertion { .api }Creates a synchronous assertion on the actual value. This is the main assertion function in Gomega.
Parameters:
actual any - The value to assert onextra ...any - Optional additional values that must be nil/zeroReturns:
Assertion - Assertion object for chaining with matchersIf Expect is passed more than one argument, it will pass the first argument to the matcher and require that all subsequent arguments are nil/zero. This is convenient for functions that return a value and an error (a common Go pattern).
Usage:
Expect("foo").To(Equal("foo"))
Expect(42).Should(BeNumerically(">", 40))
// With error checking (common Go idiom)
func FetchValue() (int, error) { ... }
Expect(FetchValue()).To(Equal(42)) // Passes only if error is nil and value is 42func Ω(actual any, extra ...any) Assertion { .api }Alias for Expect using the omega symbol (Ω). Functionally identical to Expect.
Parameters:
actual any - The value to assert onextra ...any - Optional additional values that must be nil/zeroReturns:
Assertion - Assertion object for chaining with matchersUsage:
Ω("foo").Should(Equal("foo"))
Ω(42).Should(BeNumerically(">", 40))func ExpectWithOffset(offset int, actual any, extra ...any) Assertion { .api }Like Expect but adjusts the stack trace offset for error reporting. This is useful when writing helper functions that make assertions - the error will point to the calling line rather than the helper function line.
Parameters:
offset int - Stack offset for error reportingactual any - The value to assert onextra ...any - Optional additional values that must be nil/zeroReturns:
Assertion - Assertion object for chaining with matchersUsage:
// Helper function that makes assertions
func AssertValidUser(user User) {
ExpectWithOffset(1, user.Name).NotTo(BeEmpty())
ExpectWithOffset(1, user.Age).To(BeNumerically(">", 0))
}
// In test - failures will point here, not inside AssertValidUser
AssertValidUser(myUser)The Assertion interface is returned by Expect, Ω, and ExpectWithOffset.
type Assertion interface {
Should(matcher GomegaMatcher, optionalDescription ...any) bool
ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool
To(matcher GomegaMatcher, optionalDescription ...any) bool
ToNot(matcher GomegaMatcher, optionalDescription ...any) bool
NotTo(matcher GomegaMatcher, optionalDescription ...any) bool
WithOffset(offset int) Assertion
Error() Assertion
}func (a Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }Asserts that the actual value satisfies the matcher. Typically used with Ω.
Parameters:
matcher types.GomegaMatcher - The matcher to applyoptionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Ω("foo").Should(Equal("foo"))
Ω(value).Should(BeNil(), "Expected value to be nil but got %v", value)func (a Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }Asserts that the actual value does NOT satisfy the matcher. Negated version of Should.
Parameters:
matcher types.GomegaMatcher - The matcher to apply (negated)optionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Ω(user).ShouldNot(BeNil())
Ω(list).ShouldNot(BeEmpty())func (a Assertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }Asserts that the actual value satisfies the matcher. Identical to Should, typically used with Expect.
Parameters:
matcher types.GomegaMatcher - The matcher to applyoptionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Expect("foo").To(Equal("foo"))
Expect(value).To(BeNumerically(">", 10), "Value should be greater than 10")func (a Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }Asserts that the actual value does NOT satisfy the matcher. Identical to NotTo and negated version of To.
Parameters:
matcher types.GomegaMatcher - The matcher to apply (negated)optionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Expect(user).ToNot(BeNil())
Expect(err).ToNot(HaveOccurred())func (a Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }Asserts that the actual value does NOT satisfy the matcher. Identical to ToNot and negated version of To.
Parameters:
matcher types.GomegaMatcher - The matcher to apply (negated)optionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Expect(user).NotTo(BeNil())
Expect(list).NotTo(ContainElement("forbidden"))func (a Assertion) WithOffset(offset int) Assertion { .api }Returns a new assertion with adjusted stack offset for error reporting. Useful in helper functions.
Parameters:
offset int - Stack offset adjustmentReturns:
Assertion - New assertion with offset appliedUsage:
func AssertPositive(value int) {
Expect(value).WithOffset(1).To(BeNumerically(">", 0))
}func (a Assertion) Error() Assertion { .api }Returns a new assertion that checks the last value instead of the first. This is useful when asserting on functions that return multiple values where you want to check the error (typically the last return value) specifically.
Usage:
func DoSomething() (string, int, error) { ... }
// Check the error (last value) is nil, others can be anything
Expect(DoSomething()).Error().NotTo(HaveOccurred())
// Equivalent to manually checking the error
result, count, err := DoSomething()
Expect(err).NotTo(HaveOccurred())Asynchronous assertions poll a condition repeatedly over time, either until it becomes true (Eventually) or ensuring it stays true (Consistently).
func Eventually(actualOrCtx any, args ...any) AsyncAssertion { .api }Checks that an assertion eventually passes. Eventually blocks and attempts an assertion periodically until it passes or a timeout occurs.
Parameters:
actualOrCtx any - The value to check, a function to poll, or context.Contextargs ...any - Optional timeout, polling interval, and/or context in any orderReturns:
AsyncAssertion - Asynchronous assertion object for chainingThe timeout defaults to 1 second and polling interval defaults to 10ms. These can be specified as time.Duration, parsable duration strings (e.g., "5s"), or numeric seconds.
Three Categories of Usage:
Category 1: Eventually with Values
c := make(chan bool)
go DoStuff(c)
Eventually(c, "50ms").Should(BeClosed())
// With session (from gexec)
Eventually(session).Should(gexec.Exit(0))
// With buffer (from gbytes)
Eventually(buffer).Should(gbytes.Say("hello"))Category 2: Eventually with Functions
// Function returning single value
Eventually(func() int {
return client.FetchCount()
}).Should(BeNumerically(">=", 17))
// Function returning value and error
func FetchFromDB() (string, error) { ... }
Eventually(FetchFromDB).Should(Equal("got it")) // Passes when error is nil
// With arguments
func FetchFullName(userId int) (string, error) { ... }
Eventually(FetchFullName).WithArguments(1138).Should(Equal("Wookie"))
// With context
It("fetches the correct count", func(ctx SpecContext) {
Eventually(ctx, func() int {
return client.FetchCount(ctx, "/users")
}).Should(BeNumerically(">=", 17))
}, SpecTimeout(time.Second))
// Alternative context syntax
Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17))Category 3: Eventually with Assertions Inside Functions
// Function with embedded assertions
Eventually(func(g Gomega) (Widget, error) {
ids, err := client.FetchIDs()
g.Expect(err).NotTo(HaveOccurred())
g.Expect(ids).To(ContainElement(1138))
return client.FetchWidget(1138)
}).Should(Equal(expectedWidget))
// Assertion-only function (use with Succeed())
Eventually(func(g Gomega) {
model, err := client.Find(1138)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(model.Reticulate()).To(Succeed())
g.Expect(model.IsReticulated()).To(BeTrue())
}).Should(Succeed())
// With context and arguments (Gomega must be first, context second)
Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){
tok, err := client.GetToken(ctx)
g.Expect(err).NotTo(HaveOccurred())
elements, err := client.Fetch(ctx, tok, path)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(elements).To(ConsistOf(expected))
}).WithContext(ctx).WithArguments("/names", "Joe", "Jane").Should(Succeed())Timeout and Polling Configuration:
// Using positional arguments
Eventually(myFunc, "10s", "2s").Should(BeTrue()) // 10s timeout, 2s polling
// Using chainable methods (equivalent)
Eventually(myFunc).WithTimeout(10*time.Second).WithPolling(2*time.Second).Should(BeTrue())
// With context and timeout
Eventually(client.FetchCount).WithContext(ctx).WithTimeout(10*time.Second).Should(BeTrue())func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { .api }Like Eventually but adjusts the stack trace offset for error reporting. Useful in helper functions.
Parameters:
offset int - Stack offset for error reportingactualOrCtx any - The value to check, a function to poll, or context.Contextargs ...any - Optional timeout, polling interval, and/or contextReturns:
AsyncAssertion - Asynchronous assertion object for chainingUsage:
func EventuallySucceeds(fn func() error) {
EventuallyWithOffset(1, fn).Should(Succeed())
}
// In test - failures point here, not inside helper
EventuallySucceeds(myOperation)func Consistently(actualOrCtx any, args ...any) AsyncAssertion { .api }Ensures that an assertion remains satisfied for a duration. Consistently blocks and repeatedly polls its matcher to ensure it stays satisfied. If the matcher ever fails, Consistently fails immediately.
Parameters:
actualOrCtx any - The value to check, a function to poll, or context.Contextargs ...any - Optional duration (default 100ms), polling interval (default 10ms), and/or contextReturns:
AsyncAssertion - Asynchronous assertion object for chainingThe first optional argument is the duration (defaults to 100ms), and the second is the polling interval (defaults to 10ms).
Usage:
// Ensure channel doesn't receive for 200ms
Consistently(channel, "200ms").ShouldNot(Receive())
// Ensure value stays stable
Consistently(func() int {
return counter.Get()
}).Should(Equal(5))
// With context
Consistently(ctx, func() bool {
return service.IsHealthy()
}, "1s", "100ms").Should(BeTrue())func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { .api }Like Consistently but adjusts the stack trace offset for error reporting. Useful in helper functions.
Parameters:
offset int - Stack offset for error reportingactualOrCtx any - The value to check, a function to poll, or context.Contextargs ...any - Optional duration, polling interval, and/or contextReturns:
AsyncAssertion - Asynchronous assertion object for chainingUsage:
func ConsistentlyStable(fn func() int, expected int) {
ConsistentlyWithOffset(1, fn).Should(Equal(expected))
}The AsyncAssertion interface is returned by Eventually and Consistently.
type AsyncAssertion interface {
Should(matcher GomegaMatcher, optionalDescription ...any) bool
ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool
To(matcher GomegaMatcher, optionalDescription ...any) bool
ToNot(matcher GomegaMatcher, optionalDescription ...any) bool
NotTo(matcher GomegaMatcher, optionalDescription ...any) bool
WithOffset(offset int) AsyncAssertion
WithTimeout(interval time.Duration) AsyncAssertion
WithPolling(interval time.Duration) AsyncAssertion
Within(timeout time.Duration) AsyncAssertion
ProbeEvery(interval time.Duration) AsyncAssertion
WithContext(ctx context.Context) AsyncAssertion
WithArguments(argsToForward ...any) AsyncAssertion
MustPassRepeatedly(count int) AsyncAssertion
}func (a AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }
func (a AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }
func (a AsyncAssertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }
func (a AsyncAssertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }
func (a AsyncAssertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { .api }These methods apply matchers to async assertions. Should/To expect the matcher to succeed, while ShouldNot/ToNot/NotTo expect it to fail.
Parameters:
matcher types.GomegaMatcher - The matcher to applyoptionalDescription ...any - Optional failure message or format string with argsReturns:
bool - True if assertion passed, false if it failedUsage:
Eventually(channel).Should(BeClosed())
Eventually(func() error { return client.Ping() }).Should(Succeed())
Consistently(counter).ShouldNot(BeNumerically(">", 100))func (a AsyncAssertion) WithOffset(offset int) AsyncAssertion { .api }Adjusts stack offset for error reporting.
Parameters:
offset int - Stack offset adjustmentReturns:
AsyncAssertion - Modified async assertionUsage:
Eventually(fn).WithOffset(1).Should(Succeed())func (a AsyncAssertion) WithTimeout(interval time.Duration) AsyncAssertion { .api }
func (a AsyncAssertion) Within(timeout time.Duration) AsyncAssertion { .api }Sets the timeout duration for the async assertion. Within is an alias for WithTimeout.
Parameters:
interval time.Duration / timeout time.Duration - Timeout durationReturns:
AsyncAssertion - Modified async assertionUsage:
Eventually(fn).WithTimeout(5 * time.Second).Should(Succeed())
Eventually(fn).Within(5 * time.Second).Should(Succeed()) // Same as abovefunc (a AsyncAssertion) WithPolling(interval time.Duration) AsyncAssertion { .api }
func (a AsyncAssertion) ProbeEvery(interval time.Duration) AsyncAssertion { .api }Sets the polling interval for the async assertion. ProbeEvery is an alias for WithPolling.
Parameters:
interval time.Duration - Polling intervalReturns:
AsyncAssertion - Modified async assertionUsage:
Eventually(fn).WithPolling(100 * time.Millisecond).Should(Succeed())
Eventually(fn).ProbeEvery(100 * time.Millisecond).Should(Succeed()) // Samefunc (a AsyncAssertion) WithContext(ctx context.Context) AsyncAssertion { .api }Attaches a context to the async assertion. The assertion will stop polling if the context is cancelled.
Parameters:
ctx context.Context - Context for cancellationReturns:
AsyncAssertion - Modified async assertionUsage:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
Eventually(client.FetchCount).WithContext(ctx).Should(BeNumerically(">=", 10))func (a AsyncAssertion) WithArguments(argsToForward ...any) AsyncAssertion { .api }Provides arguments to pass to the function being polled by Eventually or Consistently.
Parameters:
argsToForward ...any - Arguments to forward to the polled functionReturns:
AsyncAssertion - Modified async assertionUsage:
func FetchUser(id int) (*User, error) { ... }
Eventually(FetchUser).WithArguments(123).Should(Not(BeNil()))
// With multiple arguments
func Query(db *DB, table string, id int) (Result, error) { ... }
Eventually(Query).WithArguments(myDB, "users", 456).Should(Succeed())func (a AsyncAssertion) MustPassRepeatedly(count int) AsyncAssertion { .api }Requires that the assertion succeeds multiple times in a row before considering it satisfied. Only works with Eventually.
Parameters:
count int - Number of consecutive successful checks requiredReturns:
AsyncAssertion - Modified async assertionUsage:
// Ensure the value is stable at 100 for at least 3 checks
counter := 0
Eventually(func() int {
counter++
return counter
}).MustPassRepeatedly(3).Should(BeNumerically(">", 2))
// counter will be at least 3 when this passes
// Practical use: ensure flaky condition stabilizes
Eventually(func() bool {
return service.IsReady()
}).WithPolling(100*time.Millisecond).MustPassRepeatedly(5).Should(BeTrue())Special error types that control Eventually and Consistently behavior from within polled functions.
type PollingSignalError interface {
error
Wrap(err error) PollingSignalError
Attach(description string, obj any) PollingSignalError
Successfully() PollingSignalError
Now()
}Both StopTrying and TryAgainAfter return this interface, which provides methods for enriching the signal with additional context.
func (p PollingSignalError) Wrap(err error) PollingSignalError { .api }Wraps another error within the polling signal.
Parameters:
err error - Error to wrapReturns:
PollingSignalError - Modified polling signalfunc (p PollingSignalError) Attach(description string, obj any) PollingSignalError { .api }Attaches additional context objects to the polling signal for inclusion in failure messages.
Parameters:
description string - Description of the attached objectobj any - Object to attachReturns:
PollingSignalError - Modified polling signalfunc (p PollingSignalError) Successfully() PollingSignalError { .api }Marks the polling signal as successful. Only relevant for StopTrying with Consistently.
Returns:
PollingSignalError - Modified polling signalfunc (p PollingSignalError) Now() { .api }Triggers the polling signal immediately by panicking. Use this when you want to halt execution immediately rather than returning the error.
func StopTrying(message string) PollingSignalError { .api }Signals to Eventually or Consistently to stop polling immediately. This always results in a failure with the provided message.
Parameters:
message string - Failure messageReturns:
PollingSignalError - Polling signal errorUsage - Return as Error:
playerIndex, numPlayers := 0, 11
Eventually(func() (string, error) {
if playerIndex == numPlayers {
return "", StopTrying("no more players left")
}
name := client.FetchPlayer(playerIndex)
playerIndex++
return name, nil
}).Should(Equal("Patrick Mahomes"))Usage - Trigger Immediately:
Eventually(func() []string {
names, err := client.FetchAllPlayers()
if err == client.IRRECOVERABLE_ERROR {
StopTrying("Irrecoverable error occurred").Wrap(err).Now()
}
return names
}).Should(ContainElement("Patrick Mahomes"))With Attachments:
Eventually(func() (Result, error) {
result, err := operation()
if err != nil {
return result, StopTrying("Operation failed").
Wrap(err).
Attach("attempt", attemptCount).
Attach("last result", result)
}
return result, nil
}).Should(BeValidResult())func TryAgainAfter(duration time.Duration) PollingSignalError { .api }Adjusts the polling interval for the next iteration of Eventually or Consistently. When triggered, the polling will wait for the specified duration before the next attempt.
If the timeout occurs before the next poll, the assertion will fail with the TryAgainAfter message.
Parameters:
duration time.Duration - Duration to wait before next pollReturns:
PollingSignalError - Polling signal errorUsage - Return as Error:
Eventually(func() (string, error) {
result, retryAfter, err := client.Poll()
if err != nil {
return "", err
}
if retryAfter > 0 {
return result, TryAgainAfter(retryAfter)
}
return result, nil
}).Should(Equal("ready"))Usage - Trigger Immediately:
Eventually(func() Status {
status := client.GetStatus()
if status.State == "processing" {
TryAgainAfter(status.RetryAfter).Now()
}
return status
}).Should(HaveField("State", "complete"))With Context:
Eventually(func() error {
resp, err := api.CheckStatus()
if err != nil {
return err
}
if resp.StatusCode == 429 {
retryAfter := parseRetryAfter(resp.Header)
return TryAgainAfter(retryAfter).
Attach("rate limit", resp.Header.Get("X-RateLimit-Remaining"))
}
return nil
}).Should(Succeed())func InterceptGomegaFailures(f func()) []string { .api }Captures all failure messages from assertions within the provided function. Execution continues after each failure, allowing you to collect multiple failures.
Most useful when testing custom matchers or when you want to check a value without causing a test failure.
Parameters:
f func() - Function containing assertions to interceptReturns:
[]string - Slice of failure messages (empty if all assertions passed)Usage:
// Test a custom matcher
failures := InterceptGomegaFailures(func() {
Expect(myValue).To(MyCustomMatcher())
})
if len(failures) > 0 {
// Matcher failed with message: failures[0]
}
// Collect multiple assertion failures
failures := InterceptGomegaFailures(func() {
Expect(user.Name).To(Equal("John"))
Expect(user.Age).To(Equal(30))
Expect(user.Email).To(ContainSubstring("@"))
})
// failures will contain messages for all failed assertionsfunc InterceptGomegaFailure(f func()) error { .api }Captures the first failure from assertions within the provided function. The function stops executing at the first failed assertion.
The failure is NOT registered with the test framework - it's up to you to decide what to do with the returned error.
Parameters:
f func() - Function containing assertions to interceptReturns:
error - Error containing failure message, or nil if all assertions passedUsage:
// Check if validation would pass
err := InterceptGomegaFailure(func() {
Expect(value).To(BeNumerically(">", 0))
Expect(value).To(BeNumerically("<", 100))
})
if err != nil {
// Handle validation failure without failing the test
log.Printf("Validation failed: %v", err)
}
// Conditional assertions
err := InterceptGomegaFailure(func() {
Expect(result).To(Equal(expected))
})
if err != nil {
// Try alternative validation
Expect(result).To(BeEquivalentTo(expected))
}type Gomega = types.Gomega
type WithT = internal.Gomega
type Assertion = types.Assertion
type AsyncAssertion = types.AsyncAssertion
type PollingSignalError = internal.PollingSignalErrortype GomegaFailHandler func(message string, callerSkip ...int)Function type for failure handlers.
Parameters:
message string - Failure messagecallerSkip ...int - Optional stack offset for error reportingtype GomegaTestingT interface {
Helper()
Fatalf(format string, args ...any)
}Interface satisfied by *testing.T and compatible test types.
type Gomega interface {
Ω(actual any, extra ...any) Assertion
Expect(actual any, extra ...any) Assertion
ExpectWithOffset(offset int, actual any, extra ...any) Assertion
Eventually(actualOrCtx any, args ...any) AsyncAssertion
EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion
Consistently(actualOrCtx any, args ...any) AsyncAssertion
ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion
SetDefaultEventuallyTimeout(time.Duration)
SetDefaultEventuallyPollingInterval(time.Duration)
SetDefaultConsistentlyDuration(time.Duration)
SetDefaultConsistentlyPollingInterval(time.Duration)
EnforceDefaultTimeoutsWhenUsingContexts()
DisableDefaultTimeoutsWhenUsingContext()
}Main Gomega interface with all assertion and configuration methods.
Gomega's default timeouts and polling intervals can be configured via environment variables:
GOMEGA_DEFAULT_EVENTUALLY_TIMEOUT - Default timeout for Eventually (default: "1s")GOMEGA_DEFAULT_EVENTUALLY_POLLING_INTERVAL - Default polling for Eventually (default: "10ms")GOMEGA_DEFAULT_CONSISTENTLY_DURATION - Default duration for Consistently (default: "100ms")GOMEGA_DEFAULT_CONSISTENTLY_POLLING_INTERVAL - Default polling for Consistently (default: "10ms")GOMEGA_ENFORCE_DEFAULT_TIMEOUTS_WHEN_USING_CONTEXTS - If set, enforce default timeouts even with contextsExample:
export GOMEGA_DEFAULT_EVENTUALLY_TIMEOUT=5s
export GOMEGA_DEFAULT_EVENTUALLY_POLLING_INTERVAL=100ms
go test ./...package mypackage_test
import (
"testing"
. "github.com/onsi/gomega"
)
func TestBasicAssertions(t *testing.T) {
g := NewWithT(t)
// Simple value assertions
g.Expect(42).To(Equal(42))
g.Expect("hello").To(ContainSubstring("ell"))
g.Expect([]int{1, 2, 3}).To(HaveLen(3))
// Error handling
err := DoSomething()
g.Expect(err).NotTo(HaveOccurred())
// Multiple return values
value, err := FetchValue()
g.Expect(err).NotTo(HaveOccurred())
g.Expect(value).To(Equal("expected"))
// Or more concisely
g.Expect(FetchValue()).To(Equal("expected"))
}func TestEventuallyExamples(t *testing.T) {
g := NewWithT(t)
// Polling a channel
ch := make(chan string, 1)
go func() {
time.Sleep(100 * time.Millisecond)
ch <- "message"
}()
g.Eventually(ch).Should(Receive(Equal("message")))
// Polling a function
counter := 0
g.Eventually(func() int {
counter++
return counter
}).Should(BeNumerically(">", 5))
// With timeout and polling
g.Eventually(fetchStatus, "5s", "500ms").Should(Equal("ready"))
// With context
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
g.Eventually(ctx, func() bool {
return service.IsHealthy()
}).Should(BeTrue())
}func TestPollingControl(t *testing.T) {
g := NewWithT(t)
// Using StopTrying
attempts := 0
g.Eventually(func() (string, error) {
attempts++
if attempts > 10 {
return "", StopTrying("too many attempts")
}
result, err := tryOperation()
if err == ErrIrrecoverable {
return "", StopTrying("irrecoverable error").Wrap(err)
}
return result, err
}).Should(Equal("success"))
// Using TryAgainAfter
g.Eventually(func() (Response, error) {
resp, err := api.Poll()
if err != nil {
return resp, err
}
if resp.Status == "processing" {
return resp, TryAgainAfter(resp.RetryAfter)
}
return resp, nil
}).Should(HaveField("Status", "complete"))
}// Helper function that makes assertions
func ExpectValidUser(g Gomega, user User) {
g.ExpectWithOffset(1, user.Name).NotTo(BeEmpty())
g.ExpectWithOffset(1, user.Age).To(BeNumerically(">", 0))
g.ExpectWithOffset(1, user.Email).To(MatchRegexp(`\S+@\S+\.\S+`))
}
func TestWithHelper(t *testing.T) {
g := NewWithT(t)
user := FetchUser(123)
ExpectValidUser(g, user) // Failures point to this line, not inside helper
}func TestInterception(t *testing.T) {
g := NewWithT(t)
// Collect all failures
failures := InterceptGomegaFailures(func() {
Expect(value1).To(Equal(expected1))
Expect(value2).To(Equal(expected2))
Expect(value3).To(Equal(expected3))
})
if len(failures) > 0 {
g.Expect(failures).To(BeEmpty(), "Validation failed")
}
// Check single failure
err := InterceptGomegaFailure(func() {
Expect(user).NotTo(BeNil())
Expect(user.IsValid()).To(BeTrue())
})
if err != nil {
// Handle gracefully
t.Logf("Validation issue: %v", err)
}
}