搜索
首页后端开发Golang如何针对 Go 中的枚举对命令行标志值进行单元测试?

How to Unit Test Command Line Flag Values Against an Enumeration in Go?

在 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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
学习GO String操纵:使用'字符串”软件包学习GO String操纵:使用'字符串”软件包May 09, 2025 am 12:07 AM

Go的"strings"包提供了丰富的功能,使字符串操作高效且简单。1)使用strings.Contains()检查子串。2)strings.Split()可用于解析数据,但需谨慎使用以避免性能问题。3)strings.Join()适用于格式化字符串,但对小数据集,循环使用 =更有效。4)对于大字符串,使用strings.Builder构建字符串更高效。

GO:使用标准'字符串”包的字符串操纵GO:使用标准'字符串”包的字符串操纵May 09, 2025 am 12:07 AM

Go语言使用"strings"包进行字符串操作。1)拼接字符串使用strings.Join函数。2)查找子串使用strings.Contains函数。3)替换字符串使用strings.Replace函数,这些函数高效且易用,适用于各种字符串处理任务。

使用GO的'字节”软件包掌握字节切片操作:实用指南使用GO的'字节”软件包掌握字节切片操作:实用指南May 09, 2025 am 12:02 AM

资助bytespackageingoisesential foreffited byteSemanipulation,uperingFunctionsLikeContains,index,andReplaceForsearchingangingAndModifyingBinaryData.itenHancesperformanceNandCoderAceAnibility,MakeitiTavitalToolToolToolToolToolToolToolToolToolForhandLingBinaryData,networkProtocols,networkProtocoLss,networkProtocols,andetFilei

学习GO二进制编码/解码:使用'编码/二进制”软件包学习GO二进制编码/解码:使用'编码/二进制”软件包May 08, 2025 am 12:13 AM

Go语言使用"encoding/binary"包进行二进制编码与解码。1)该包提供binary.Write和binary.Read函数,用于数据的写入和读取。2)需要注意选择正确的字节序(如BigEndian或LittleEndian)。3)数据对齐和错误处理也是关键,确保数据的正确性和性能。

GO:带有标准'字节”软件包的字节切​​片操作GO:带有标准'字节”软件包的字节切​​片操作May 08, 2025 am 12:09 AM

1)usebybytes.joinforconcatenatinges,2)bytes.bufferforincrementalWriter,3)bytes.indexorbytes.indexorbytes.indexbyteforsearching bytes.bytes.readereforrednerncretinging.isnchunk.ss.ind.inc.softes.4)

进行编码/二进制包:优化二进制操作的性能进行编码/二进制包:优化二进制操作的性能May 08, 2025 am 12:06 AM

theencoding/binarypackageingoiseforporptimizingBinaryBinaryOperationsDuetoitssupportforendiannessessandefficityDatahandling.toenhancePerformance:1)usebinary.nativeendiandiandiandiandiandiandiandian nessideendian toavoid avoidByteByteswapping.2)

Go Bytes软件包:简短的参考和提示Go Bytes软件包:简短的参考和提示May 08, 2025 am 12:05 AM

Go的bytes包主要用于高效处理字节切片。1)使用bytes.Buffer可以高效进行字符串拼接,避免不必要的内存分配。2)bytes.Equal函数用于快速比较字节切片。3)bytes.Index、bytes.Split和bytes.ReplaceAll函数可用于搜索和操作字节切片,但需注意性能问题。

Go Bytes软件包:字节切片操纵的实例Go Bytes软件包:字节切片操纵的实例May 08, 2025 am 12:01 AM

字节包提供了多种功能来高效处理字节切片。1)使用bytes.Contains检查字节序列。2)用bytes.Split分割字节切片。3)通过bytes.Replace替换字节序列。4)用bytes.Join连接多个字节切片。5)利用bytes.Buffer构建数据。6)结合bytes.Map进行错误处理和数据验证。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。