The Gomega DSL provides functions for creating assertions, integrating with test frameworks, and configuring assertion behavior. It supports both synchronous assertions (Expect, Ω) and asynchronous assertions (Eventually, Consistently).
Creates an assertion on an actual value.
func Expect(actual any, extra ...any) AssertionParameters:
actual: The value to assert onextra: Optional additional values that must be nil/zero (useful for function returns)Returns: Assertion interface with methods Should, ShouldNot, To, ToNot, NotTo
Usage:
// Basic assertion
Expect(value).To(Equal(42))
// With extra values (e.g., error checking)
value, err := GetValue()
Expect(value).To(Equal("expected")) // Fails if err != nil
// Negation
Expect(value).ToNot(BeNil())
Expect(value).ShouldNot(BeEmpty())Like Expect but adjusts the call stack offset for error reporting.
func ExpectWithOffset(offset int, actual any, extra ...any) AssertionParameters:
offset: Call stack offset for error messagesactual: The value to assert onextra: Optional additional values that must be nil/zeroReturns: Assertion
Usage:
// In a helper function, offset by 1 to show correct file:line
func AssertEqual(t *testing.T, actual, expected any) {
ExpectWithOffset(1, actual).To(Equal(expected))
}Identical to Expect. Provides alternative syntax using the Greek omega symbol.
func Ω(actual any, extra ...any) AssertionParameters:
actual: The value to assert onextra: Optional additional values that must be nil/zeroReturns: Assertion
Usage:
Ω(value).Should(Equal(42))
Ω(value, err).Should(Equal("expected")) // Fails if err != nilPolls a value or function until an assertion passes or timeout is reached.
func Eventually(actualOrCtx any, args ...any) AsyncAssertionParameters:
actualOrCtx: Value, function returning value(s), or context.Contextargs: Optional timeout and polling interval (time.Duration values)Returns: AsyncAssertion interface
Timeout/Interval Resolution:
Usage:
// Poll function until it returns true
Eventually(func() bool {
return counter.Value() == 10
}).Should(BeTrue())
// With timeout and polling interval
Eventually(isReady, 5*time.Second, 100*time.Millisecond).Should(BeTrue())
// With context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
Eventually(ctx, func() bool {
return checkCondition()
}).Should(BeTrue())
// Poll value directly (re-evaluated each poll)
Eventually(counter.Value).Should(Equal(10))
// With channel
Eventually(ch).Should(Receive())Advanced Usage:
// Fluent configuration
Eventually(func() int {
return queue.Size()
}).WithTimeout(10 * time.Second).
WithPolling(500 * time.Millisecond).
Should(Equal(0))
// Must pass repeatedly (passes N times in a row before succeeding)
Eventually(flaky).MustPassRepeatedly(3).Should(BeTrue())
// With arguments passed to function
Eventually(func(arg1 int, arg2 string) bool {
return process(arg1, arg2)
}).WithArguments(42, "test").Should(BeTrue())Like Eventually but with custom call stack offset for error reporting.
func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertionParameters:
offset: Call stack offset for error messagesactualOrCtx: Value, function, or context.Contextargs: Optional timeout and polling intervalReturns: AsyncAssertion
Polls a value or function and requires the assertion to pass for the entire duration.
func Consistently(actualOrCtx any, args ...any) AsyncAssertionParameters:
actualOrCtx: Value, function returning value(s), or context.Contextargs: Optional duration and polling interval (time.Duration values)Returns: AsyncAssertion interface
Duration/Interval Resolution:
Usage:
// Verify condition stays true for duration
Consistently(func() bool {
return service.IsHealthy()
}).Should(BeTrue())
// With custom duration and polling
Consistently(isStable, 2*time.Second, 50*time.Millisecond).Should(BeTrue())
// With context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Consistently(ctx, func() int {
return activeConnections.Count()
}).Should(BeNumerically("<", 100))Like Consistently but with custom call stack offset for error reporting.
func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertionParameters:
offset: Call stack offset for error messagesactualOrCtx: Value, function, or context.Contextargs: Optional duration and polling intervalReturns: AsyncAssertion
Connects Gomega to a test framework by registering a fail handler function.
func RegisterFailHandler(fail types.GomegaFailHandler)Parameters:
fail: Function called when assertion fails: func(message string, callerSkip ...int)Usage:
// With Ginkgo
import . "github.com/onsi/ginkgo/v2"
func TestMyPackage(t *testing.T) {
RegisterFailHandler(Fail) // Ginkgo's Fail function
RunSpecs(t, "MyPackage Suite")
}
// Custom fail handler
RegisterFailHandler(func(message string, callerSkip ...int) {
log.Fatalf("Assertion failed: %s", message)
})Creates a WithT instance for use with testing.T or compatible test frameworks.
func NewWithT(t types.GomegaTestingT) *WithTParameters:
t: testing.T or any type implementing GomegaTestingT interface (has Helper() and Fatalf(format, args...))Returns: *WithT with Expect, Eventually, Consistently methods
Usage:
func TestMyFeature(t *testing.T) {
g := NewWithT(t)
value := DoSomething()
g.Expect(value).To(Equal("expected"))
g.Eventually(func() bool {
return checkReady()
}).Should(BeTrue())
}Deprecated. Registers testing.T with the global Default Gomega instance. Use NewWithT() instead for fresh instance per test.
func RegisterTestingT(t types.GomegaTestingT)Parameters:
t: testing.T or compatible interfaceDeprecated. Use RegisterFailHandler or RegisterTestingT instead.
func RegisterFailHandlerWithT(_ types.GomegaTestingT, fail types.GomegaFailHandler)Creates a new Gomega instance with a custom fail handler. Useful for non-test scenarios or collecting failures without failing the test.
func NewGomega(fail types.GomegaFailHandler) GomegaParameters:
fail: Custom fail handler functionReturns: Gomega interface with full DSL
Usage:
// Create Gomega that collects failures instead of failing
var failures []string
g := NewGomega(func(message string, callerSkip ...int) {
failures = append(failures, message)
})
g.Expect(value1).To(Equal("expected1"))
g.Expect(value2).To(Equal("expected2"))
// Check collected failures
if len(failures) > 0 {
log.Printf("Validation failures: %v", failures)
}The global default Gomega instance used by package-level functions.
var Default = Gomega(internal.NewGomega(internal.FetchDefaultDurationBundle()))Usage:
Most users don't interact with Default directly - package-level functions like Expect() use it automatically.
Runs a callback and returns the first failure message as an error, stopping execution on first failure.
func InterceptGomegaFailure(f func()) (err error)Parameters:
f: Callback function to runReturns: error wrapping the first failure message, or nil if no failures
Usage:
// Test a custom matcher without failing the test
err := InterceptGomegaFailure(func() {
Expect(value).To(MyCustomMatcher())
})
if err != nil {
t.Logf("Matcher failed as expected: %v", err)
}
// Validate multiple items, stop on first failure
err = InterceptGomegaFailure(func() {
Expect(result.Name).To(Equal("expected"))
Expect(result.Value).To(BeNumerically(">", 0))
})Runs a callback and returns all failure messages, continuing execution after failures.
func InterceptGomegaFailures(f func()) []stringParameters:
f: Callback function to runReturns: Slice of all failure messages
Usage:
// Collect all failures
failures := InterceptGomegaFailures(func() {
Expect(result.Name).To(Equal("expected"))
Expect(result.Value).To(BeNumerically(">", 0))
Expect(result.Status).To(Equal("active"))
})
if len(failures) > 0 {
t.Logf("Found %d validation failures:", len(failures))
for _, f := range failures {
t.Log(f)
}
}Sets the default timeout for Eventually assertions.
func SetDefaultEventuallyTimeout(t time.Duration)Parameters:
t: Timeout duration (default: 1 second)Sets the default polling interval for Eventually assertions.
func SetDefaultEventuallyPollingInterval(t time.Duration)Parameters:
t: Polling interval (default: 10 milliseconds)Sets the default duration for Consistently assertions.
func SetDefaultConsistentlyDuration(t time.Duration)Parameters:
t: Duration (default: 100 milliseconds)Sets the default polling interval for Consistently assertions.
func SetDefaultConsistentlyPollingInterval(t time.Duration)Parameters:
t: Polling interval (default: 10 milliseconds)Disables default timeouts when using context.Context with Eventually/Consistently. The context's deadline becomes the only timeout.
func DisableDefaultTimeoutsWhenUsingContext()Enforces default timeouts even when using context.Context (default behavior). The shorter of the context deadline and default timeout is used.
func EnforceDefaultTimeoutsWhenUsingContexts()Special errors that control polling behavior in Eventually/Consistently.
Signal error that stops Eventually/Consistently polling and fails the assertion.
var StopTrying = internal.StopTryingUsage:
Eventually(func() error {
result, err := TryOperation()
if err != nil {
if isFatal(err) {
return StopTrying // Stop polling, fail now
}
return err // Continue polling
}
return nil
}).Should(Succeed())Signal function that delays the next poll by a custom duration.
var TryAgainAfter = internal.TryAgainAfterUsage:
Eventually(func() error {
result, err := TryOperation()
if err != nil {
if isRateLimited(err) {
return TryAgainAfter(5 * time.Second) // Wait 5s before next attempt
}
return err
}
return nil
}).Should(Succeed())Type alias for the Gomega interface.
type Gomega = types.GomegaType alias for WithT (testing.T integration).
type WithT = internal.GomegaDeprecated alias for WithT.
type GomegaWithT = WithTType alias for the Assertion interface.
type Assertion = types.AssertionType alias for the AsyncAssertion interface.
type AsyncAssertion = types.AsyncAssertionType alias for Assertion.
type GomegaAssertion = types.AssertionType alias for AsyncAssertion.
type GomegaAsyncAssertion = types.AsyncAssertionType alias for GomegaMatcher.
type OmegaMatcher = types.GomegaMatcherType alias for polling signal errors.
type PollingSignalError = internal.PollingSignalErrorconst GOMEGA_VERSION = "1.38.2"