登录
首页 >  Golang >  Go问答

如何编写测试来检查特定类型的变量?

来源:stackoverflow

时间:2024-04-27 17:33:39 163浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《如何编写测试来检查特定类型的变量?》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有一个返回特定类型客户端的函数,我想通过检查返回的变量类型是否为 azblob.blockblobclient 类型来测试该函数。

当我使用简单的 if 语句来检查如下类型时: if var == azblob.blockblobclient 我收到错误 azblob.blockblobclient (type) is not an expression

使用标准 testing 包测试变量类型的正确方法是什么?

提前非常感谢!

//函数

func getclient(blob, container string) azblob.blockblobclient {
  storageaccount := os.getenv("azure_storage_account_name")
  
  cred, err := azidentity.newdefaultazurecredential(nil)
  if err != nil {
      log.fatal("invalid credentials with error:" + err.error())
  }

  bloburl := fmt.sprintf("https://%s.blob.core.windows.net/%s/%s", storageaccount, container, blob)
  fmt.println(bloburl)
  client, err := azblob.newblockblobclient(bloburl, cred, nil)
  if err != nil {
      log.fatal("unable to create blob client")
  }
  return client
}

//测试

package main 

import (
    "testing"
    "os"
    "github.com/azure/azure-sdk-for-go/sdk/storage/azblob"
)

func testgetclient(t *testing.t){
  blob := "text.txt"
  container := "testcontainer"
  os.setenv("azure_storage_account_name", "mystorageaccount")
  client := getclient(blob, container)
  
  if client != azblob.blockblobclient {
    t.errorf("client should be type blockblobclient")
  }
}

正确答案


您实际上不需要这样做,因为您编写的函数仅返回 azblob.blockblobclient 类型,编译器将在构建测试之前检查这一点。如果不是这种情况,测试将无法运行。

我做了以下更改来显示这一点:

//函数

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/azure/azure-sdk-for-go/sdk/storage/azblob"
)

func getclient(blob, container string) interface{} {
    storageaccount := os.getenv("azure_storage_account_name")

    cred, err := azidentity.newdefaultazurecredential(nil)
    if err != nil {
        log.fatal("invalid credentials with error:" + err.error())
    }

    bloburl := fmt.sprintf("https://%s.blob.core.windows.net/%s/%s", storageaccount, container, blob)
    fmt.println(bloburl)
    client, err := azblob.newblockblobclient(bloburl, cred, nil)
    if err != nil {
        log.fatal("unable to create blob client")
    }
    return client
}

//测试

package main

import (
    "os"
    "testing"

    "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)

func TestgetClient(t *testing.T) {
    blob := "text.txt"
    container := "testcontainer"
    os.Setenv("AZURE_STORAGE_ACCOUNT_NAME", "mystorageaccount")
    client := getClient(blob, container)

    _, ok := client.(azblob.BlockBlobClient)
    if !ok {
        t.Errorf("client should be type BlockBlobClient")
    }
}

到这里,我们也就讲完了《如何编写测试来检查特定类型的变量?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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