我有一個回傳特定型別客戶端的函式,我想通過檢查回傳的變數的型別是否為 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")
}
}
uj5u.com熱心網友回復:
您實際上不需要這樣做,因為您撰寫的函式僅回傳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")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453009.html
上一篇:教程第一步MicrosoftGo
