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

我有一个返回特定类型客户端的函数,我想通过检查返回的变量类型是否为 type 来测试该函数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")

  }

}


小怪兽爱吃肉
浏览 81回答 1
1回答

莫回无

你真的不需要这样做,因为你写的函数只返回azblob.BlockBlobClient类型,编译器甚至会在构建测试之前检查它。如果不是这种情况,测试将无法运行。我做了以下更改以显示这一点://函数package mainimport (    "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 mainimport (    "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")    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go