I have a table-driven test and init var(worker
) outside table loop. I run the test with go test -raсe
and added t.Parallel()
and no race condition was detected. Can I assume that my test free of race condition
:
//This mock could be in a separate file.
type mockWorker struct {
}
// implment our Worker iterface
func(md mockWorker)Work()error{
return nil
}
type mockDoer struct{
Error error
Worker worker
}
// implment our Doer iterface
func(md mockDoer)Do()error{
if err := md.Worker.Work(); err != nil {
return err
}
return md.Error
}
func TestBusinessDoer(t *testing.T){
t.Parallel()
worker := mockWorker{}
cases := []struct{
Name string
ExpectError bool
Error error
}{
{
Name:"test does business logic",
ExpectError : false,
Error : nil,
},
{
Name:"test fails when dependency errors",
ExpectError : true,
Error : errors.New("an error"),
},
}
for _,td := range cases{
t.Run(td.Name, func (t *testing.T){
doer := mockDoer{Error: td.Error, Worker: worker}
err := mything.BusinessDoer(doer)
if td.ExpectError && err == nil{
t.Fatalf("expected an error but got none")
}
if ! td.ExpectError && err != nil{
t.Fatalf("did not expect an error but got one %s ", err.Error())
}
})
}
}
I think you need to run the sub tests in parallel.
Can you call t.Parallel() inside the subtests and check ?
td := td
t.Run(td.Name, func (t *testing.T){
t.Parallel()
doer := mockDoer{Error: td.Error, Worker: worker}
err := mything.BusinessDoer(doer)
if td.ExpectError && err == nil{
t.Fatalf("expected an error but got none")
}
if ! td.ExpectError && err != nil{
t.Fatalf("did not expect an error but got one %s ", err.Error())
}
})
Some links to refer to make it parallel: https://gist.github.com/posener/92a55c4cd441fc5e5e85f27bca008721
https://rakyll.org/parallelize-test-tables/