是否有任何使用 testify 编写干净表驱动测试的示例。输入和预期输出的表驱动测试效果很好,但必须测试依赖项的输出似乎真的很难做到。
下面的示例使用一个模拟接口,并要求我编写一个全新的测试函数来验证被测函数是否正确处理依赖错误。我只是在寻找建议,以使使用 testify 模拟包更简化编写单元测试。
package packageone
import (
"errors"
"musings/packageone/mocks"
"testing"
)
//Regular Table driven test
func TestTstruct_DoSomething(t *testing.T) {
testObj := new(mocks.Dinterface)
passes := []struct {
Input int
Output int
}{{0, 0}, {1, 1}, {2, 4}, {100, 10000}}
for _, i := range passes {
testObj.On("DoSomethingWithD", i.Input).Return(i.Output, nil)
}
type fields struct {
DC Dinterface
}
type args struct {
i int
}
tests := []struct {
name string
fields fields
args args
wantRes int
wantErr bool
}{
{"Pass#0", fields{testObj}, args{passes[0].Input}, passes[0].Output, false},
{"Pass#1", fields{testObj}, args{passes[1].Input}, passes[1].Output, false},
{"Pass#2", fields{testObj}, args{passes[2].Input}, passes[2].Output, false},
{"Pass#3", fields{testObj}, args{passes[3].Input}, passes[3].Output, false},
{"Fail#4", fields{testObj}, args{-1}, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := &Tstruct{
DC: tt.fields.DC,
}
gotRes, err := r.DoSomething(tt.args.i)
if (err != nil) != tt.wantErr {
t.Errorf("Tstruct.DoSomething() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotRes != tt.wantRes {
t.Errorf("Tstruct.DoSomething() = %v, want %v", gotRes, tt.wantRes)
}
})
}
}
//Separate Unit test for dependency returning errors.
func TestTstruct_ErrMock_DoSomething(t *testing.T) {
testObj := new(mocks.Dinterface)
testObj.On("DoSomethingWithD", 1).Return(0, errors.New(""))
type fields struct {
DC Dinterface
}
type args struct {
i int
}
tests := []struct {
name string
fields fields
args args
wantRes int
wantErr bool
}{
{"Test#1", fields{testObj}, args{1}, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := &Tstruct{
DC: tt.fields.DC,
}
gotRes, err := r.DoSomething(tt.args.i)
if (err != nil) != tt.wantErr {
t.Errorf("Tstruct.DoSomething() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotRes != tt.wantRes {
t.Errorf("Tstruct.DoSomething() = %v, want %v", gotRes, tt.wantRes)
}
})
}
}