[Go] Check slice elements in any order with assert

Created on November 28, 2026

You can use ElementsMatch from the assert package to check that a slice contains the expected elements in any order.

First, define the ReturnSlice function to test. It returns a fixed slice.

package main

func ReturnSlice() []string {
    return []string{"one", "two", "three"}
}

Next, create a file to test ReturnSlice.

package main

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestReturnSlice(t *testing.T) {
    assert := assert.New(t)

    got := ReturnSlice()
    assert.ElementsMatch([]string{"three", "one", "two"}, got)
}
  • assert.New(t) initializes a value of type *assert.Assertions.
  • assert.ElementsMatch([]string{"three", "one", "two"}, got) checks whether the slice contains the expected elements. The test passes because the slices contain the same elements, regardless of their order.
Go