How to test that a function was called in a goroutine?

1.5k Views Asked by At

I'd like to make sure that we're starting a goroutine by calling a function with the right arguments.

For example:

func MyTest(t *testing.T) {
    service.EXPECT().MyMockFunc(1)
    service.MyFunc()
}

func MyFunc() {
    go MyMockFunc(1)
}

When I run this test, it fails because (I believe) MyMockFunc only gets called after the test has already finished running.

Is there a way to test that I started a goroutine by calling a function with the right arguments?

Note: Ideally, I'd like to keep the arguments I pass to MyMockFunc as is (not add a channel arg for instance).

1

There are 1 best solutions below

1
On

Using a channel and assuming you can fire the goroutine from the test:

package main

import (
    "fmt"
    "testing"
    "time"
)

func MyMockFunc(n int) int {
    fmt.Println("MyMockFunc is called")
    time.Sleep(5 * time.Second)
    return n + 1
}

func TestMyMockFunc(t *testing.T) {
    result := make(chan int)
    go func() {
        result <- MyMockFunc(1)
    }()
    if <-result != 2 {
        t.Fatalf("Expecting 2")
    }
}