Gomega is Ginkgo's Preferred Matcher Library - a BDD-style matcher library for Go testing
npx @tessl/cli install tessl/golang-gomega@1.38.0Gomega 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.
go get github.com/onsi/gomegaimport (
"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
)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"))
})
})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"))
}package main
import (
. "github.com/onsi/gomega"
)
func main() {
RegisterFailHandler(func(message string, callerSkip ...int) {
panic(message)
})
value := ComputeValue()
Expect(value).To(BeNumerically(">", 0))
}Gomega is organized into several key components:
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) *WithTOver 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.GomegaMatcherTest 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.GomegaMatcherBuild 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.GomegaMatcherCreate 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.HandlerFuncAdvanced 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.GomegaMatcherBenchmark 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) *ExperimentDetect 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.GomegaMatcherBuild 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.GomegaMatcherCore 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
}// 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")))// 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())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// 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"))// Set default Eventually timeout
SetDefaultEventuallyTimeout(5 * time.Second)
SetDefaultEventuallyPollingInterval(100 * time.Millisecond)
// Set default Consistently duration
SetDefaultConsistentlyDuration(2 * time.Second)
SetDefaultConsistentlyPollingInterval(50 * time.Millisecond)ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Eventually respects context cancellation
Eventually(ctx, func() bool {
return checkCondition()
}).Should(BeTrue())Gomega version: 1.38.2
const GOMEGA_VERSION = "1.38.2"