Skip to content

mholzen/test-utils-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

test-utils-go

A Go module providing test helpers for common testing scenarios.

Installation

go get github.com/mholzen/test-utils-go

Usage

Generic Assertions

Check if a collection contains elements matching a predicate:

package mypackage

import (
    "testing"
    testutils "github.com/mholzen/test-utils-go"
)

type Foo struct {
    ID   int
    Name string
}

func TestExample(t *testing.T) {
    foos := []Foo{
        {ID: 1, Name: "Alice"},
        {ID: 2, Name: "Bob"},
    }

    // Assert that collection contains an element matching the predicate
    testutils.AssertContains(t, foos, func(foo Foo) bool { return foo.ID == 1 })

    // Assert that collection doesn't contain an element matching the predicate
    testutils.AssertNotContains(t, foos, func(foo Foo) bool { return foo.ID == 99 })

    // Works with any type
    numbers := []int{1, 2, 3, 4, 5}
    testutils.AssertContains(t, numbers, func(n int) bool { return n > 4 })
}

File Assertions

Check if a file contains or doesn't contain a specific string:

package mypackage

import (
    "testing"
    testutils "github.com/mholzen/test-utils-go"
)

func TestExample(t *testing.T) {
    // Assert that a file contains a string
    testutils.AssertFileContains(t, "output.txt", "expected content")

    // Assert that a file doesn't contain a string
    testutils.AssertFileNotContains(t, "output.txt", "should not be present")
}

API

AssertContains[T any](t *testing.T, collection []T, predicate func(T) bool)

Checks if a collection contains at least one element that satisfies the predicate. Fails the test if no element matches the predicate.

AssertNotContains[T any](t *testing.T, collection []T, predicate func(T) bool)

Checks if a collection does not contain any element that satisfies the predicate. Fails the test if any element matches the predicate.

AssertFileContains(t *testing.T, filePath, expected string)

Checks if a file contains the expected string. Fails the test if:

  • The file cannot be read
  • The file doesn't contain the expected string

AssertFileNotContains(t *testing.T, filePath, unexpected string)

Checks if a file does not contain the given string. Fails the test if:

  • The file cannot be read
  • The file contains the unexpected string

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages