Github.com/stretchr/testify: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 51: Line 51:
{{External|https://pkg.go.dev/github.com/stretchr/testify/mock}}
{{External|https://pkg.go.dev/github.com/stretchr/testify/mock}}


Mocking with Testify is based on the assumption that we want to construct [[Software_Testing_Concepts#Mock|mock instances]] to replace in testing real instances defined by [[Go_Interfaces#Overview|interfaces]]. We define such a mock instance, we instantiate it with <code>new()</code> or <code>&SomeInterfaceMock{}</code>, we configure it (Testify calls this "setting up expectations"), we pass it to the code that needs to be tested, we run the code, and then we ensure the code behave correctly. We can also "assert expectations" on the mock.
Mocking with Testify is based on the assumption that we want to construct [[Software_Testing_Concepts#Mock|mock instances]] to replace in testing real instances, standing in for external dependencies,  defined by [[Go_Interfaces#Overview|interfaces]]. We define such a mock instance, we instantiate it with <code>new()</code> or <code>&SomeInterfaceMock{}</code>, we configure it (Testify calls this "setting up expectations"), we pass it to the code that needs to be tested, we run the code, and then we ensure the code behave correctly. We can also "assert expectations" on the mock.





Revision as of 21:27, 6 March 2024

External

Internal

Overview

Installation

go get github.com/stretchr/testify

Programming Model

Assertions

package yours

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

func TestSomething(t *testing.T) {

  assert := tassert.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)
  }
}

To check that an error has the expected message:

err := ...
assert.NotNil(err)
assert.Equal(err.Error(), "expected message")

Mocks

https://pkg.go.dev/github.com/stretchr/testify/mock

Mocking with Testify is based on the assumption that we want to construct mock instances to replace in testing real instances, standing in for external dependencies, defined by interfaces. We define such a mock instance, we instantiate it with new() or &SomeInterfaceMock{}, we configure it (Testify calls this "setting up expectations"), we pass it to the code that needs to be tested, we run the code, and then we ensure the code behave correctly. We can also "assert expectations" on the mock.


...
type MockMyService struct {
	mock.Mock
}

func (m * MockMyService) Start() error {
  ...
}

...

mockMyService := new(MockMyService)