0

I have a problem with running tests in Go that require a mocked call. I have several test cases with different parameters and for each I also create an expected call for gomock to mock.

service := NewService()

tests := map[string]struct{
    param1 string
    param2 string
    ...
    expected bool
}{
    "test1":{"1", ...},
    "test2":{"2", ...},
    "test3":{"3", ...},
}

gomock.InOrder(
    // test1
    storer.EXPECT().Get("1").Return(...)

    // test2
    storer.EXPECT().Get("2").Return(...)
    
    // test3
    storer.EXPECT().Get("3").Return(...)
)

for name, test := range tests {
    t.Run(name, func(t *testing.T) {
        res := service.FUNCTION_TO_TEST(test.param1, test.param2, test.param3, ...)

        assert.Equal(t, test.expected, res)
    })

Function that is tested calls storer.Get(string)

Now to the problem I am experiencing:
When I first run the whole test, everything works. If I run it again, gomock starts throwing errors that expected function call doesn't have a prerequisite call satisfied. It seems that go doesn't run the subtests in order they are in the map. When I added printing subtest names to terminal I could clearly see that the first subtest running wasn't "test1", but sometimes it was "test2", sometimes "test3."
If I debug the whole test, everything works.
go clean -cache sometimes helps, now not.

Thanks for any help!

KronwarsCZ
  • 21
  • 3
  • Also to add, I checked the documentation for package testing to see if there was some parallelism happening, but not - t.Run() does start new goroutine, but blocks the main program until it returns. – KronwarsCZ Aug 17 '22 at 13:46
  • I still don't know what is happening, but I found an alternate solution: In the tests struct I can add a function, that only calls the storer.EXPECT()..., and I call this function just before a subtest starts. – KronwarsCZ Aug 18 '22 at 06:27

0 Answers0