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

tessl/golang-gomega

Gomega is Ginkgo's Preferred Matcher Library - a BDD-style matcher library for Go testing

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/onsi/gomega@1.38.x

To install, run

npx @tessl/cli install tessl/golang-gomega@1.38.0

index.mddocs/

Gomega

Gomega is a matcher/assertion library for Go testing, designed for use with the Ginkgo BDD testing framework but also usable standalone with Go's standard testing package or any testing framework. It provides a rich, expressive DSL for writing test assertions with over 70 built-in matchers and support for asynchronous testing patterns.

Package Information

  • Package Name: gomega
  • Package Type: Go module
  • Language: Go
  • Module Path: github.com/onsi/gomega
  • Installation: go get github.com/onsi/gomega

Core Imports

import (
    "github.com/onsi/gomega"
    . "github.com/onsi/gomega" // Dot import for DSL functions
)

For specific sub-packages:

import (
    "github.com/onsi/gomega/gbytes"   // Byte stream testing
    "github.com/onsi/gomega/gexec"    // Process execution testing
    "github.com/onsi/gomega/ghttp"    // HTTP server testing
    "github.com/onsi/gomega/gstruct"  // Struct field matching
    "github.com/onsi/gomega/gmeasure" // Performance measurement
    "github.com/onsi/gomega/gleak"    // Goroutine leak detection
    "github.com/onsi/gomega/gcustom"  // Custom matcher creation
    "github.com/onsi/gomega/types"    // Core type definitions
)

Basic Usage

With Ginkgo

package mypackage_test

import (
    . "github.com/onsi/ginkgo/v2"
    . "github.com/onsi/gomega"
    "testing"
)

func TestMyPackage(t *testing.T) {
    RegisterFailHandler(Fail)
    RunSpecs(t, "MyPackage Suite")
}

var _ = Describe("MyFeature", func() {
    It("should work correctly", func() {
        result := DoSomething()
        Expect(result).To(Equal("expected value"))
    })
})

With testing.T

package mypackage_test

import (
    . "github.com/onsi/gomega"
    "testing"
)

func TestMyFeature(t *testing.T) {
    g := NewWithT(t)

    result := DoSomething()
    g.Expect(result).To(Equal("expected value"))
}

Standalone

package main

import (
    . "github.com/onsi/gomega"
)

func main() {
    RegisterFailHandler(func(message string, callerSkip ...int) {
        panic(message)
    })

    value := ComputeValue()
    Expect(value).To(BeNumerically(">", 0))
}

Architecture

Gomega is organized into several key components:

  • Core DSL: Assertion functions (Expect, Eventually, Consistently) and configuration
  • Matchers: 70+ built-in matchers for various data types and scenarios
  • Sub-packages: Specialized testing utilities (gbytes, gexec, ghttp, etc.)
  • Types: Core interfaces and type definitions
  • Format: Value formatting for failure messages

Capabilities

Core Assertions and DSL

Gomega provides synchronous assertions (Expect, Ω) and asynchronous assertions (Eventually, Consistently) with configurable timeouts and polling intervals. Supports integration with Ginkgo, testing.T, or custom fail handlers.

// Synchronous assertions
func Expect(actual any, extra ...any) Assertion
func Ω(actual any, extra ...any) Assertion

// Asynchronous assertions
func Eventually(actualOrCtx any, args ...any) AsyncAssertion
func Consistently(actualOrCtx any, args ...any) AsyncAssertion

// Setup and configuration
func RegisterFailHandler(fail types.GomegaFailHandler)
func NewWithT(t types.GomegaTestingT) *WithT

Core Assertions and DSL

Matchers

Over 70 built-in matchers covering equality, types, collections, strings, errors, channels, HTTP, files, and more. Matchers can be combined with And, Or, and Not for complex assertions.

// Equality matchers
func Equal(expected any) types.GomegaMatcher
func BeEquivalentTo(expected any) types.GomegaMatcher
func BeIdenticalTo(expected any) types.GomegaMatcher

// Collection matchers
func ContainElement(element any, result ...any) types.GomegaMatcher
func ConsistOf(elements ...any) types.GomegaMatcher
func HaveLen(count int) types.GomegaMatcher

// String matchers
func ContainSubstring(substr string, args ...any) types.GomegaMatcher
func MatchRegexp(regexp string, args ...any) types.GomegaMatcher

// Error matchers
func HaveOccurred() types.GomegaMatcher
func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher

Matchers

Byte Stream Testing (gbytes)

Test I/O operations with thread-safe buffers that support pattern matching on streaming content. Useful for testing command output, logs, and other byte streams.

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

func NewBuffer() *Buffer
func Say(expected any, args ...any) types.GomegaMatcher

Byte Stream Testing

Process Execution Testing (gexec)

Build and test external processes with easy access to stdout, stderr, and exit codes. Includes utilities for building Go binaries and managing test processes.

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

func Start(command *exec.Cmd, outWriter, errWriter io.Writer) (*Session, error)
func Build(packagePath string, args ...string) (string, error)
func Exit(optionalExitCode ...int) types.GomegaMatcher

Process Execution Testing

HTTP Testing (ghttp)

Create fake HTTP servers for testing HTTP clients with configurable handlers, request verification, and canned responses. Supports both HTTP and HTTPS.

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

func NewServer() *Server
func RespondWith(statusCode int, body any, optionalHeader ...http.Header) http.HandlerFunc
func VerifyRequest(method string, path any, rawQuery ...any) http.HandlerFunc

HTTP Testing

Struct Field Matching (gstruct)

Advanced matchers for validating struct fields, map keys, and array elements with support for nested structures and partial matching.

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

func MatchFields(options FieldsOptions, fields Fields) types.GomegaMatcher
func MatchAllFields(fields Fields) types.GomegaMatcher
func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher

Struct Field Matching

Performance Measurement (gmeasure)

Benchmark and measure code performance with statistical analysis. Create experiments, record measurements, and generate formatted reports.

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

func NewExperiment(name string) *Experiment

Performance Measurement

Goroutine Leak Detection (gleak)

Detect goroutine leaks in tests by comparing goroutines before and after test execution with support for filtering known background goroutines.

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

func IgnoreCurrent() IgnoredGoroutines
func HaveLeaked(options ...IgnoredGoroutines) types.GomegaMatcher

Goroutine Leak Detection

Custom Matcher Creation (gcustom)

Build custom matchers with type-safe APIs using generics. Simplifies creating domain-specific matchers for your tests.

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

func MakeMatcher[T any](match func(actual T) (bool, error)) types.GomegaMatcher
func MakeMatcherWithMessage[T any](
    match func(actual T) (bool, error),
    message func(actual T, failure bool) string,
) types.GomegaMatcher

Custom Matcher Creation

Core Types and Interfaces

Core type definitions and interfaces that define Gomega's contract. Use these when building extensions or understanding the framework's architecture.

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

type GomegaMatcher interface {
    Match(actual any) (success bool, err error)
    FailureMessage(actual any) string
    NegatedFailureMessage(actual any) string
}

type Assertion interface {
    Should(matcher GomegaMatcher, optionalDescription ...any) bool
    To(matcher GomegaMatcher, optionalDescription ...any) bool
    // ... more methods
}

Core Types and Interfaces

Common Patterns

Error Handling

// Check if error occurred
err := DoSomething()
Expect(err).ShouldNot(HaveOccurred())

// Or more concisely
Expect(DoSomething()).Should(Succeed())

// Match specific error
Expect(err).To(MatchError("expected error message"))
Expect(err).To(MatchError(ContainSubstring("connection")))

Asynchronous Testing

// Poll until condition is met (default 1s timeout)
Eventually(func() int {
    return counter.Value()
}).Should(Equal(10))

// With timeout and polling interval
Eventually(isReady, 5*time.Second, 100*time.Millisecond).Should(BeTrue())

// Consistently check condition stays true
Consistently(func() bool {
    return service.IsHealthy()
}, 2*time.Second).Should(BeTrue())

Collection Assertions

slice := []int{1, 2, 3, 4, 5}

Expect(slice).To(HaveLen(5))
Expect(slice).To(ContainElement(3))
Expect(slice).To(ConsistOf(1, 2, 3, 4, 5)) // Order-independent
Expect(slice).To(HaveExactElements(1, 2, 3, 4, 5)) // Order matters

Multiple Return Values

// When function returns (value, error), extra values must be nil/zero
value, err := GetValue()
Expect(value).To(Equal("expected")) // Automatically fails if err != nil

// Equivalent to:
Expect(err).ShouldNot(HaveOccurred())
Expect(value).To(Equal("expected"))

Configuration

Timeout Configuration

// Set default Eventually timeout
SetDefaultEventuallyTimeout(5 * time.Second)
SetDefaultEventuallyPollingInterval(100 * time.Millisecond)

// Set default Consistently duration
SetDefaultConsistentlyDuration(2 * time.Second)
SetDefaultConsistentlyPollingInterval(50 * time.Millisecond)

Context Support

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

// Eventually respects context cancellation
Eventually(ctx, func() bool {
    return checkCondition()
}).Should(BeTrue())

Version

Gomega version: 1.38.2

const GOMEGA_VERSION = "1.38.2"