登录
首页 >  Golang >  Go问答

学习 Go 语言中接口和模拟的概念

来源:stackoverflow

时间:2024-02-28 12:00:26 177浏览 收藏

大家好,今天本人给大家带来文章《学习 Go 语言中接口和模拟的概念》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在尝试为 aws 服务 ( ecr ) 构建抽象。这是代码:

type ecr struct {
    client ecriface.ecrapi
    ctx    context.context
}

// ecrcreate establishes aws session and creates a repo with provided input
func (e *ecr) ecrcreate(ecrinput *ecr.createrepositoryinput) {

    result, err := e.client.createrepositorywithcontext(e.ctx, ecrinput)
    if err != nil {
        if aerr, ok := err.(awserr.error); ok {
            switch aerr.code() {
            case ecr.errcodeserverexception:
                log.errorln(ecr.errcodeserverexception, aerr.error())
            case ecr.errcodeinvalidparameterexception:
                log.errorln(ecr.errcodeinvalidparameterexception, aerr.error())
            case ecr.errcodeinvalidtagparameterexception:
                log.errorln(ecr.errcodeinvalidtagparameterexception, aerr.error())
            case ecr.errcodetoomanytagsexception:
                log.errorln(ecr.errcodetoomanytagsexception, aerr.error())
            case ecr.errcoderepositoryalreadyexistsexception:
                log.errorln(ecr.errcoderepositoryalreadyexistsexception, aerr.error())
            case ecr.errcodelimitexceededexception:
                log.errorln(ecr.errcodelimitexceededexception, aerr.error())
            case ecr.errcodekmsexception:
                log.errorln(ecr.errcodekmsexception, aerr.error())
            default:
                log.errorln(aerr.error())
            }
        } else {
            // print the error, cast err to awserr.error to get the code and
            // message from an error.
            log.errorln(err.error())
        }
        return
    }
    log.infof("result: %v", result)
}

模拟 aws sdk 创建存储库调用:

type mockECRClient struct {
    ecriface.ECRAPI
}

func (m *mockECRClient) CreateRepositoryWithContext(ctx aws.Context, input *ecr.CreateRepositoryInput, opts ...request.Option) (*ecr.CreateRepositoryOutput, error) {
    createdAt := time.Now()
    encryptionType := "AES256"
    //awsMockAccount := "974589621236"
    encryptConfig := ecr.EncryptionConfiguration{EncryptionType: &encryptionType}
    imageScanConfig := input.ImageScanningConfiguration

    mockRepo := ecr.Repository{
        CreatedAt:                  &createdAt,
        EncryptionConfiguration:    &encryptConfig,
        ImageScanningConfiguration: imageScanConfig,
    }

    mockRepoOuput := ecr.CreateRepositoryOutput{Repository: &mockRepo}

    return &mockRepoOuput, nil

}

func TestECR_ECRCreate(t *testing.T) {
    ctx := context.TODO()
    mockSvc := &mockECRClient{}
    scan := true
    name := "Test1"
    inputTest1 := ecr.CreateRepositoryInput{
        RepositoryName:             &name,
        ImageScanningConfiguration: &ecr.ImageScanningConfiguration{ScanOnPush: &scan},
    }

    ecrTest := ECR{
        mockSvc,
        ctx,
    }

    ecrTest.ECRCreate(&inputTest1)
}

这有效。然而,我对这里接口和组合的使用有点困惑。 ecrapi 由 ecriface 包定义,我实现了该接口的签名之一,并且仍然能够使用模拟客户端 mocksvc。 问题:

  • 这是如何运作的?这是模拟接口的惯用方式吗?
  • ecrapi 接口的其他方法怎么样?这些是如何照顾的?

我的理解是否正确,我们可以定义一个具有任意数量的方法签名的接口,将该接口嵌入到一个结构中,然后将该结构传递到需要接口的地方。但这意味着,我跳过实现界面的其他签名?

我想我在这里遗漏了一些重要的概念,请指出!


解决方案


简短的回答是:这是有效的,因为测试的函数仅调用您显式定义的方法。如果它调用其他任何东西,它就会失败。

事情是这样发生的:

mockecrclient 结构嵌入了接口,因此它具有该接口的所有方法。但是,要调用任何这些方法,您必须将该接口设置为实现:

x:=mockECRClient{}
x.ECRAPI=

对 x.func() 的调用(其中 func 是为 ecrapi 定义的)实际上会调用 x.ecrapi.func()。由于您没有设置 ecrapi,因此上面的 x.ecrapi 为 nil,并且您调用的任何使用接收器的方法都会出现恐慌。

但是,您为 mockecrclient 定义了一个方法:createrepositorywithcontext。当您调用x.createrepositorywithcontext时,该方法属于x而不是x.ecrapi,并且接收者将是x,因此它可以工作。

今天关于《学习 Go 语言中接口和模拟的概念》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>