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

How do you write tests for checking vars of a specific type?

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

当我使用一个简单的 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")
  }
}

你真的不需要这样做,因为你写的函数只有 returns 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")
    }
}