测试函数是否被调用

问题描述 投票:1回答:1

鉴于此结构和功能:

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

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

我怎样才能进行单元测试以确保在运行SomeFunc函数时调用A

go testing gomega
1个回答
2
投票
  1. 你可以模拟界面的实现,比如
globalIndex
type Mock struct{}

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

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

  1. 试试testifyAssertExpectations可以帮助你

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

© www.soinside.com 2019 - 2024. All rights reserved.