我有一个表驱动的测试,并在表循环外进行了var(worker
)初始化。我使用go test -raсe
进行了测试,并添加了t.Parallel()
,但未检测到竞争状况。我可以假设我的测试没有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())
}
})
}
}
答案 0 :(得分:0)
我认为您需要并行运行子测试。
您可以在子测试中调用t.Parallel()并检查吗?
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())
}
})
一些引用使其平行:
https://gist.github.com/posener/92a55c4cd441fc5e5e85f27bca008721
https://rakyll.org/parallelize-test-tables/