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

错误的断言包含并等于未按预期工作

错误的断言包含并等于未按预期工作

Go
白衣非少年 2022-08-01 18:58:38
我正在断言函数中的错误,我已经为函数提供了这样的输入,以便它将引发错误。我想检查错误是否正确。这是我的函数:func validateK8ResourcesLength(resource prm.Resource) error {    name := resource.GetName()    namespace := resource.GetNamespace()    k8sResourceName := fmt.Sprintf("%s-%s", namespace, name)    if len(k8sResourceName) > common.K8sNameLength {        return fmt.Errorf("Namespace (%s) and Name (%s) length combined must not be greater than 48 chars", namespace, name)    }    return nil}我的测试代码:func TestK8testing(t *testing.T) {    ctrl := gomock.NewController(t)    defer ctrl.Finish()    mockContext := prmmock.NewMockStepContext(ctrl)    mockResource := prmmock.NewMockResource(ctrl)    mockClient := prmmock.NewMockClient(ctrl)    // testClient := fake.NewFakeClientWithScheme(runtime.NewScheme())    lables := make(map[string]string)    mockClient.EXPECT().GetResource(gomock.Any(), gomock.Any()).Return(mockResource, nil).AnyTimes()    mockContext.EXPECT().Resource().Return(mockResource).AnyTimes()    mockResource.EXPECT().GetKind().Return("data-movement-v1-nonexist").AnyTimes()    mockResource.EXPECT().GetName().Return("test-dm-more-then-forty-eight-charactors-this-should-fail").AnyTimes()    mockResource.EXPECT().GetNamespace().Return("ns-more-then-forty-eight-charactors-this-should-fail").AnyTimes()    mockResource.EXPECT().GetLabels().Return(lables).AnyTimes()    mockResource.EXPECT().GetID().Return(prm.NewResourceID("hcc-dm", "data-movement-v1", "test-dm")).AnyTimes()    err := validateK8ResourcesLength(mockResource)    assert.Error(t, err)    if assert.Error(t, err) {        //assert.Contains(t, err, "length combined must not be greater")        assert.Equal(t, "Namespace (ns-more-then-forty-eight-charactors-this-should-fail) and Name (test-dm-more-then-forty-eight-charactors-this-should-fail) length combined must not be greater than 48 chars", err)    }}我的代码有什么问题?我也不起作用。assert.contains
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

错误内置类型是一个接口:

type error interface {
    Error() string
    }

因此,如果要检查错误值,则实际上需要调用该方法。Error() string

此资源介绍了基础知识:https://blog.golang.org/error-handling-and-go

以及 Go 1.13 对基础知识的扩展:https://blog.golang.org/go1.13-errors


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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