亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

您如何編寫測試來檢查特定類型的變量?

您如何編寫測試來檢查特定類型的變量?

Go
小怪獸愛吃肉 2022-11-23 20:29:46
我有一個返回特定類型客戶端的函數,我想通過檢查返回的變量類型是否為 type 來測試該函數azblob.BlockBlobClient。當我使用一個簡單的if語句來檢查這樣的類型時:if var == azblob.BlockBlobClient我得到了錯誤azblob.BlockBlobClient (type) is not an expressiontesting使用標準包測試變量類型的正確方法是什么?非常感謝!//函數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")  }}
查看完整描述

1 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

你真的不需要這樣做,因為你寫的函數只返回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")

    }

}


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號