繁体   English   中英

function 的单元测试,在其中启动 go 例程

[英]Unit testing of a function that starts a go routine inside it

我有一个大致如下的代码库

type Service struct {
    Repo                 repo // An interface that contains both FunctionOne and FunctionTwo
    GoRoutineWaitgroup   *sync.WaitGroup
}

func (impl *Service) MyFunction(s string) bool {
    a := impl.Repo.FunctionOne()
    b := impl.Repo.FunctionTwo()
    fmt.Println("Executed Function One and Function two")
    go impl.validateMyFunction(a,b)
    return true

}

func (impl *Service) validateMyFunction(a string,b string) {
    defer helpers.PanicHandler()
    impl.GoRoutineWaitgroup.Add(1)
    defer impl.GoRoutineWaitgroup.Done()

    fmt.Println("a and b are validated")
}

我编写了与此类似的单元测试。

func TestMyFunction(t *testing.T) {

     ms := &Service{}

     test := []struct{
                 input string
                 output bool
                 case string
             }{
                 {"a", true, sample}
              }
     }

    for _, test := range tests {
        t.Run(test.case, func(t *testing.T) {

            mockRepo := new(mockrepo.Repo) // mockRepo contains mocks of original repo layer methods generated using mockery for testing purposes

            mockRepo.On("FunctionOne")
            mockRepo.On("FunctionTwo")

            ms.Repo = mockRepo

            op := ms.MyFunction(test.input)
            assert.Equal(t, test.Output, op)
        })
    }

} // Please keep in mind that this is not my actual code, but just a basic structure.

所有测试均成功。 但是在执行命令go test -v时,我在代码中的多个地方看到程序出现恐慌并给出了invalid memory address or nil pointer dereference 我在调试模式下检查了代码,发现问题出在方法validateMyFunction中的impl.GoRoutineWaitgroup.Add(1)上,当我注释掉go validateMyFunction(a,b)并再次运行测试时,日志中没有出现恐慌。 那么我该如何解决这个问题呢? 如何处理从内部启动 goroutine 的函数的单元测试(如本例所示)?

您需要初始化GoRoutineWaitgroup字段的值。

ms := &Service{GoRoutineWaitgroup: &sync.WaitGroup{}}

或从定义中删除指针

type Service struct {
    Repo                 repo 
    GoRoutineWaitgroup   sync.WaitGroup
}

此外,我没有在您的代码中看到等待等待组。 ms.GoRoutineWaitgroup.Wait()类的东西,您需要将 impl.GoRoutineWaitgroup.Add(1) 从validateMyFunction移动到MyFunction否则validateMyFunction中的代码将不会被调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM