为了账号安全,请及时绑定邮箱和手机立即绑定

如何正确测试错误对象?

如何正确测试错误对象?

Go
GCT1015 2022-07-25 11:08:13
所以让我们假设我有一个我想测试的功能。这个函数看起来像这样:func coolFunction(input int) (error, int) {  if input == 1 {    err := error.New("This is an error")    number := 400  } else {    err := nil    number := 200  }  return err, number}如果我想测试这个函数,有正面和负面的情况,我必须写一个这样的测试函数:func TestCoolFunction(t *testing.T) {    type args struct {        input int    }    tests := []struct {        name         string        args         args        wantError    error        wantInt      int    }{        {"No error",             args{                0,            },             nil,            200,             },    }}所以这很好用。但是我将如何测试错误对象不是的否定情况nil?我的目标是知道 if error != nil,所以测试显示 PASS 作为结果,同时使用上述结构。有任何想法吗?
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

如果我理解正确,您想在某些条件下检查正确的错误返回。


这是:


func coolFunction(input int) (int, error) {

    var err error

    var number int

    if input == 1 {

        err = errors.New("This is an error")

        number = 400

    } else {

        err = nil

        number = 200

    }


    return number, err

}

然后在测试文件中,您需要对您期望错误的事实有一个理解或协议(正确地)。就像下面的标志一样expectError bool,这对于您的情况来说是正确的。


您还可以拥有特定错误类型的字段并检查返回的类型是否正是该类型。


func TestCoolFunction(t *testing.T) {


    var testTable = []struct {

        desc        string

        in          int

        expectError bool

        out         int

    }{

        {"Should_fail", 1, true, 0},

        {"Should_pass", 100, false, 200},

    }


    for _, tt := range testTable {


        t.Run(tt.desc, func(t *testing.T) {

            out, err := coolFunction(tt.in)

            if tt.expectError {

                if err == nil {

                    t.Error("Failed")

                }

            } else {

                if out != tt.out {

                    t.Errorf("got %d, want %d", out, tt.out)

                }

            }

        })


    }

}

DeepEqual使用@mkopriva 建议的添加特定错误检查


func TestCoolFunction(t *testing.T) {


    var testTable = []struct {

        desc        string

        in          int

        expectError error

        out         int

    }{

        {"Should_fail", 1, errors.New("This is an error"), 0},

        {"Should_pass", 100, nil, 200},

    }


    for _, tt := range testTable {


        t.Run(tt.desc, func(t *testing.T) {

            out, err := coolFunction(tt.in)

            if tt.expectError != nil {

                if !reflect.DeepEqual(err, tt.expectError) {

                    t.Error("Failed")

                }

            } else {

                if out != tt.out {

                    t.Errorf("got %d, want %d", out, tt.out)

                }

            }

        })


    }

}

同样DeepEqual是为了演示,您实际上应该使用一些不同的方法来检查错误,这样更快。这取决于您的应用程序中错误的设计方式。您可以使用标记错误或类型/接口检查。或自定义错误类型中基于 const 的枚举字段。


查看完整回答
反对 回复 2022-07-25
  • 1 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号