Test whether a function was called

484 views Asked by At

Given this struct and function:

type ExampleModule struct {
  DB                   *database.Store
  AnotherModule        AnotherModuleInterface
}

func(m *ExampleModule) A (i int, id int[]) error{
  err := m.AnotherModuke.SomeFunc(i, id)
}

How can I make a unit test to make sure that SomeFunc is called when I run the function A?

1

There are 1 answers

0
Pan Ke On
  1. you can mock implementation of the interface, like
globalIndex
type Mock struct{}

func (m Mock) SomeFunc(){
    globalIndex++
}

func testA(t *testing.T) {
    a := ExampleModule{
        AnotherModule: Mock{},
    }
    a.A()
    assert(globalIndex == 1)
}

  1. try testify. AssertExpectations can help you

https://github.com/stretchr/testify#mock-package