在 Go 中測試命令列標誌
本文探討了 Golang 中命令列標誌的測試技術。具體來說,我們將研究如何針對枚舉對標誌值進行單元測試。
問題陳述
給出以下程式碼:
<code class="go">// Define flag for output format var formatType string // Constants representing valid format types const ( text = "text" json = "json" hash = "hash" ) // Initialize flags func init() { flag.StringVar(&formatType, "format", "text", "Desired output format") } // Main function func main() { flag.Parse() }</code>
我們希望寫一個單元測試來驗證-format 標誌值是否與預定義常量之一匹配。
使用自訂標誌類型的解決方案
要在更多中測試標誌以靈活的方式,我們可以利用flag.Var 函數和實作Value 介面的自訂類型。
<code class="go">package main import ( "errors" "flag" "fmt" ) // Custom type representing format type type formatType string // String() method for Value interface func (f *formatType) String() string { return fmt.Sprint(*f) } // Set() method for Value interface func (f *formatType) Set(value string) error { if len(*f) > 0 && *f != "text" { return errors.New("format flag already set") } if value != "text" && value != "json" && value != "hash" { return errors.New("Invalid Format Type") } *f = formatType(value) return nil } // Initialize flag with custom type func init() { typeFlag := "text" // Default value usage := `Format type. Must be "text", "json" or "hash". Defaults to "text".` flag.Var(&typeFlag, "format", usage) } // Main function func main() { flag.Parse() fmt.Println("Format type is", typeFlag) } </code>
在此解決方案中,flag.Var 接受一個指向滿足 Value 介面的自訂類型的指針,允許我們在 Set 方法中定義自己的驗證邏輯。
單元測試自訂標誌類型
自訂標誌類型的單元測試可以編寫如下:
<code class="go">// Test unit validates that the format flag is within the enumeration func TestFormatFlag(t *testing.T) { testCases := []struct { input string expectedErr string }{ {"text", ""}, {"json", ""}, {"hash", ""}, {"", "Invalid Format Type"}, {"xml", "Invalid Format Type"}, } for _, tc := range testCases { t.Run(tc.input, func(t *testing.T) { args := []string{"-format", tc.input} flag.CommandLine = flag.NewFlagSet("test", flag.PanicOnError) err := flag.CommandLine.Parse(args) if err != nil && err.Error() != tc.expectedErr { t.Errorf("Unexpected error: %v", err) return } }) } }</code>
以上是如何針對 Go 中的枚舉對命令列標誌值進行單元測試?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

你應該關心Go語言中的"strings"包,因為它提供了處理文本數據的工具,從基本的字符串拼接到高級的正則表達式匹配。 1)"strings"包提供了高效的字符串操作,如Join函數用於拼接字符串,避免性能問題。 2)它包含高級功能,如ContainsAny函數,用於檢查字符串是否包含特定字符集。 3)Replace函數用於替換字符串中的子串,需注意替換順序和大小寫敏感性。 4)Split函數可以根據分隔符拆分字符串,常用於正則表達式處理。 5)使用時需考慮性能,如

“編碼/二進制”軟件包interingoisentialForHandlingBinaryData,oferingToolSforreDingingAndWritingBinaryDataEfficely.1)Itsupportsbothlittle-endianandBig-endianBig-endianbyteorders,CompialforOss-System-System-System-compatibility.2)

掌握Go語言中的bytes包有助於提高代碼的效率和優雅性。 1)bytes包對於解析二進制數據、處理網絡協議和內存管理至關重要。 2)使用bytes.Buffer可以逐步構建字節切片。 3)bytes包提供了搜索、替換和分割字節切片的功能。 4)bytes.Reader類型適用於從字節切片讀取數據,特別是在I/O操作中。 5)bytes包與Go的垃圾回收器協同工作,提高了大數據處理的效率。

你可以使用Go語言中的"strings"包來操縱字符串。 1)使用strings.TrimSpace去除字符串兩端的空白字符。 2)用strings.Split將字符串按指定分隔符拆分成切片。 3)通過strings.Join將字符串切片合併成一個字符串。 4)用strings.Contains檢查字符串是否包含特定子串。 5)利用strings.ReplaceAll進行全局替換。注意使用時要考慮性能和潛在的陷阱。

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

thealternativestogo'sbytespackageincageincludethestringspackage,bufiopackage和customstructs.1)thestringspackagecanbeusedforbytemanipulationforbytemanipulationbybyconvertingbytestostostostostostrings.2))

“字節”包裝封裝forefforeflyManipulatingByteslices,CocialforbinaryData,網絡交易和andfilei/o.itoffersfunctionslikeIndexForsearching,BufferForhandLinglaRgedLargedLargedAtaTasets,ReaderForsimulatingStreamReadReadImreAmreadReamReadinging,以及Joineffiter和Joineffiter和Joineffore

go'sstringspackageIscialforficientficientsTringManipulation,uperingToolSlikestrings.split(),strings.join(),strings.replaceall(),andStrings.contains.contains.contains.contains.contains.contains.split.split(split()strings.split()dividesStringoSubSubStrings; 2)strings.joins.joins.joinsillise.joinsinelline joinsiline joinsinelline; 3);


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3 Linux新版
SublimeText3 Linux最新版

WebStorm Mac版
好用的JavaScript開發工具