Convert Figma logo to code with AI

stretchr logotestify

A toolkit with common assertions and mocks that plays nicely with the standard library

22,996
1,580
22,996
405

Top Related Projects

9,298

GoMock is a mocking framework for the Go programming language.

8,225

A Modern Testing Framework for Go

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

1,764

Professional lightweight testing mini-framework for Go.

Quick Overview

The stretchr/testify project is a collection of packages that provide a set of assertions and mocks for the Go programming language. It is designed to make writing tests in Go more expressive, readable, and maintainable.

Pros

  • Expressive Assertions: The project provides a wide range of assertion functions that make it easy to write clear and concise test cases.
  • Mocking Capabilities: The project includes a mocking framework that allows you to easily create and configure mocks for your tests.
  • Compatibility: The project is compatible with the standard Go testing framework, making it easy to integrate into existing projects.
  • Active Development: The project is actively maintained and regularly updated, with a large and engaged community of contributors.

Cons

  • Dependency Management: The project has a relatively large number of dependencies, which can make it more challenging to manage in some projects.
  • Learning Curve: The project has a relatively large API, which can take some time to learn and become comfortable with.
  • Potential Overhead: The use of the project's assertions and mocks can add some overhead to your tests, which may be a concern in performance-critical applications.
  • Limited Ecosystem: While the project is widely used, it may not have the same level of ecosystem support as some other testing frameworks in the Go community.

Code Examples

Here are a few examples of how to use the stretchr/testify library in Go:

Assertion Example

package main

import (
    "testing"

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

func TestAddition(t *testing.T) {
    result := 2 + 2
    assert.Equal(t, 4, result, "the sum of 2 and 2 should equal 4")
}

This example demonstrates how to use the assert.Equal() function to check that the result of an addition operation is equal to the expected value.

Mocking Example

package main

import (
    "testing"

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

type MyService struct {
    Dependency *MyDependency
}

type MyDependency struct {
    mock.Mock
}

func (m *MyDependency) DoSomething(arg string) error {
    args := m.Called(arg)
    return args.Error(0)
}

func TestMyService(t *testing.T) {
    // Create a mock dependency
    mockDependency := &MyDependency{}
    mockDependency.On("DoSomething", "test").Return(nil)

    // Create the service and inject the mock dependency
    service := MyService{Dependency: mockDependency}

    // Call the service method and assert that the mock was called
    err := service.Dependency.DoSomething("test")
    assert.NoError(t, err)
    mockDependency.AssertExpectations(t)
}

This example demonstrates how to use the mock.Mock type to create a mock dependency and use it in a test case.

Getting Started

To get started with the stretchr/testify library, you can follow these steps:

  1. Install the library using the Go package manager:
go get github.com/stretchr/testify
  1. Import the necessary packages in your Go file:
import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
)
  1. Use the assertion and mocking functions provided by the library in your test cases:
func TestMyFunction(t *testing.T) {
    // Use assert functions to make assertions
    assert.Equal(t, 4, 2+2, "the sum of 2 and 2 should equal 4")

    // Use mock functions to create and configure mocks
    mockDependency := &MyDependency{}
    mockDependency.On("DoSomething", "test").Return(nil)

    // Use the mocked dependency in your test case
    service := MyService{Dependency: mockDependency}
    err := service.Dependency

Competitor Comparisons

9,298

GoMock is a mocking framework for the Go programming language.

Pros of mock

  • Generates mock implementations automatically, reducing boilerplate code
  • Integrates well with Go's built-in testing package
  • Provides more fine-grained control over mock behavior

Cons of mock

  • Steeper learning curve compared to testify's simpler assertion functions
  • Requires code generation step, which can complicate the build process
  • Less extensive set of assertion functions for general testing scenarios

Code Comparison

mock:

ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockObj := NewMockInterface(ctrl)
mockObj.EXPECT().SomeMethod(gomock.Any()).Return(42)

testify:

mockObj := new(MockObject)
mockObj.On("SomeMethod", mock.Anything).Return(42)
assert.Equal(t, 42, mockObj.SomeMethod("input"))

Summary

mock excels in generating mock implementations and providing detailed control over mock behavior, making it suitable for complex mocking scenarios. testify offers a more straightforward approach with its extensive set of assertion functions and easier setup, making it ideal for general testing needs. The choice between the two depends on the specific requirements of your testing strategy and the complexity of your mocking needs.

8,225

A Modern Testing Framework for Go

Pros of Ginkgo

  • Provides a BDD-style testing framework with a focus on readability and expressiveness
  • Offers powerful test organization features like nested describe blocks and BeforeEach/AfterEach hooks
  • Includes built-in support for asynchronous testing and parallel test execution

Cons of Ginkgo

  • Steeper learning curve compared to Testify's simpler assertion-based approach
  • May be considered overkill for smaller projects or simpler test suites
  • Requires additional setup and configuration compared to Testify's more straightforward usage

Code Comparison

Ginkgo:

var _ = Describe("Calculator", func() {
    It("adds two numbers", func() {
        result := Add(2, 3)
        Expect(result).To(Equal(5))
    })
})

Testify:

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    assert.Equal(t, 5, result)
}

Both Ginkgo and Testify are popular testing frameworks for Go, but they cater to different testing styles and project needs. Ginkgo offers a more structured and expressive approach to testing, while Testify provides a simpler, assertion-based method. The choice between the two depends on the project's complexity, team preferences, and specific testing requirements.

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

Pros of goconvey

  • Provides a web UI for real-time test results and coverage reports
  • Supports automatic test running on file changes
  • Offers a more expressive and readable syntax for writing tests

Cons of goconvey

  • Less widely adopted compared to testify
  • May have a steeper learning curve for developers familiar with Go's standard testing package
  • Limited to Go testing, while testify can be used with other testing frameworks

Code Comparison

goconvey:

Convey("Given a user", t, func() {
    user := NewUser("John")
    Convey("When the name is retrieved", func() {
        name := user.Name()
        So(name, ShouldEqual, "John")
    })
})

testify:

func TestUser(t *testing.T) {
    user := NewUser("John")
    assert := assert.New(t)
    assert.Equal("John", user.Name())
}

Both goconvey and testify are popular testing libraries for Go, each with its own strengths. goconvey offers a more descriptive and nested approach to writing tests, along with a web UI for visualizing results. testify, on the other hand, provides a simpler syntax that closely resembles Go's standard testing package, making it easier for developers to adopt. The choice between the two often depends on personal preference and project requirements.

1,764

Professional lightweight testing mini-framework for Go.

Pros of is

  • Simpler and more concise API, focusing on a single is function
  • Easier to read and understand for beginners
  • Lightweight with minimal dependencies

Cons of is

  • Less feature-rich compared to testify
  • Fewer assertion types and helper functions
  • Limited support for advanced testing scenarios

Code Comparison

testify:

assert.Equal(t, expected, actual)
assert.NotNil(t, value)
assert.True(t, condition)

is:

is.Equal(t, actual, expected)
is.True(t, value != nil)
is.True(t, condition)

Both libraries provide assertion functions for Go testing, but they differ in their approach and feature set. testify offers a more comprehensive suite of testing tools, including mocking capabilities and a wider range of assertion types. It's well-suited for complex testing scenarios and larger projects.

is, on the other hand, focuses on simplicity and readability. It provides a single is function with various assertion types, making it easier for beginners to get started with testing in Go. However, it may lack some advanced features found in testify.

Ultimately, the choice between these libraries depends on the project's complexity and the team's preferences. testify is more suitable for larger projects with diverse testing needs, while is is ideal for smaller projects or teams prioritizing simplicity and ease of use.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Testify - Thou Shalt Write Tests

ℹ️ We are working on testify v2 and would love to hear what you'd like to see in it, have your say here: https://cutt.ly/testify

Build Status Go Report Card PkgGoDev

Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend.

Features include:

Get started:

assert package

The assert package provides some helpful methods that allow you to write better test code in Go.

  • Prints friendly, easy to read failure descriptions
  • Allows for very readable code
  • Optionally annotate each assertion with a message

See it in action:

package yours

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

func TestSomething(t *testing.T) {

  // assert equality
  assert.Equal(t, 123, 123, "they should be equal")

  // assert inequality
  assert.NotEqual(t, 123, 456, "they should not be equal")

  // assert for nil (good for errors)
  assert.Nil(t, object)

  // assert for not nil (good when you expect something)
  if assert.NotNil(t, object) {

    // now we know that object isn't nil, we are safe to make
    // further assertions without causing any errors
    assert.Equal(t, "Something", object.Value)

  }

}
  • Every assert func takes the testing.T object as the first argument. This is how it writes the errors out through the normal go test capabilities.
  • Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions.

if you assert many times, use the below:

package yours

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

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

  // assert equality
  assert.Equal(123, 123, "they should be equal")

  // assert inequality
  assert.NotEqual(123, 456, "they should not be equal")

  // assert for nil (good for errors)
  assert.Nil(object)

  // assert for not nil (good when you expect something)
  if assert.NotNil(object) {

    // now we know that object isn't nil, we are safe to make
    // further assertions without causing any errors
    assert.Equal("Something", object.Value)
  }
}

require package

The require package provides same global functions as the assert package, but instead of returning a boolean result they terminate current test. These functions must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Otherwise race conditions may occur.

See t.FailNow for details.

mock package

The mock package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code.

An example test function that tests a piece of code that relies on an external object testObj, can set up expectations (testify) and assert that they indeed happened:

package yours

import (
  "testing"
  "github.com/stretchr/testify/mock"
)

/*
  Test objects
*/

// MyMockedObject is a mocked object that implements an interface
// that describes an object that the code I am testing relies on.
type MyMockedObject struct{
  mock.Mock
}

// DoSomething is a method on MyMockedObject that implements some interface
// and just records the activity, and returns what the Mock object tells it to.
//
// In the real object, this method would do something useful, but since this
// is a mocked object - we're just going to stub it out.
//
// NOTE: This method is not being tested here, code that uses this object is.
func (m *MyMockedObject) DoSomething(number int) (bool, error) {

  args := m.Called(number)
  return args.Bool(0), args.Error(1)

}

/*
  Actual test functions
*/

// TestSomething is an example of how to use our test object to
// make assertions about some target code we are testing.
func TestSomething(t *testing.T) {

  // create an instance of our test object
  testObj := new(MyMockedObject)

  // set up expectations
  testObj.On("DoSomething", 123).Return(true, nil)

  // call the code we are testing
  targetFuncThatDoesSomethingWithObj(testObj)

  // assert that the expectations were met
  testObj.AssertExpectations(t)


}

// TestSomethingWithPlaceholder is a second example of how to use our test object to
// make assertions about some target code we are testing.
// This time using a placeholder. Placeholders might be used when the
// data being passed in is normally dynamically generated and cannot be
// predicted beforehand (eg. containing hashes that are time sensitive)
func TestSomethingWithPlaceholder(t *testing.T) {

  // create an instance of our test object
  testObj := new(MyMockedObject)

  // set up expectations with a placeholder in the argument list
  testObj.On("DoSomething", mock.Anything).Return(true, nil)

  // call the code we are testing
  targetFuncThatDoesSomethingWithObj(testObj)

  // assert that the expectations were met
  testObj.AssertExpectations(t)


}

// TestSomethingElse2 is a third example that shows how you can use
// the Unset method to cleanup handlers and then add new ones.
func TestSomethingElse2(t *testing.T) {

  // create an instance of our test object
  testObj := new(MyMockedObject)

  // set up expectations with a placeholder in the argument list
  mockCall := testObj.On("DoSomething", mock.Anything).Return(true, nil)

  // call the code we are testing
  targetFuncThatDoesSomethingWithObj(testObj)

  // assert that the expectations were met
  testObj.AssertExpectations(t)

  // remove the handler now so we can add another one that takes precedence
  mockCall.Unset()

  // return false now instead of true
  testObj.On("DoSomething", mock.Anything).Return(false, nil)

  testObj.AssertExpectations(t)
}

For more information on how to write mock code, check out the API documentation for the mock package.

You can use the mockery tool to autogenerate the mock code against an interface as well, making using mocks much quicker.

suite package

The suite package provides functionality that you might be used to from more common object-oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal.

An example suite is shown below:

// Basic imports
import (
    "testing"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/suite"
)

// Define the suite, and absorb the built-in basic suite
// functionality from testify - including a T() method which
// returns the current testing context
type ExampleTestSuite struct {
    suite.Suite
    VariableThatShouldStartAtFive int
}

// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
    suite.VariableThatShouldStartAtFive = 5
}

// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
    assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive)
}

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
    suite.Run(t, new(ExampleTestSuite))
}

For a more complete example, using all of the functionality provided by the suite package, look at our example testing suite

For more information on writing suites, check out the API documentation for the suite package.

Suite object has assertion methods:

// Basic imports
import (
    "testing"
    "github.com/stretchr/testify/suite"
)

// Define the suite, and absorb the built-in basic suite
// functionality from testify - including assertion methods.
type ExampleTestSuite struct {
    suite.Suite
    VariableThatShouldStartAtFive int
}

// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
    suite.VariableThatShouldStartAtFive = 5
}

// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
    suite.Equal(suite.VariableThatShouldStartAtFive, 5)
}

// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
    suite.Run(t, new(ExampleTestSuite))
}

Installation

To install Testify, use go get:

go get github.com/stretchr/testify

This will then make the following packages available to you:

github.com/stretchr/testify/assert
github.com/stretchr/testify/require
github.com/stretchr/testify/mock
github.com/stretchr/testify/suite
github.com/stretchr/testify/http (deprecated)

Import the testify/assert package into your code using this template:

package yours

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

func TestSomething(t *testing.T) {

  assert.True(t, true, "True is true!")

}

Staying up to date

To update Testify to the latest version, use go get -u github.com/stretchr/testify.


Supported go versions

We currently support the most recent major Go versions from 1.19 onward.


Contributing

Please feel free to submit issues, fork the repository and send pull requests!

When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it.

Code generation is used. Look for Code generated with at the top of some files. Run go generate ./... to update generated files.

We also chat on the Gophers Slack group in the #testify and #testify-dev channels.


License

This project is licensed under the terms of the MIT license.