搜索
首页后端开发GolangGolang 单元测试的简单错误问题

Golang 单元测试的简单错误问题

Golang单元测试是保证代码质量和功能正确性的重要手段,但在实践中,我们常常会遇到一些简单的错误问题。在本文中,php小编子墨将为大家介绍一些常见的错误问题,以及如何解决它们。通过学习这些问题的解决方法,相信大家在进行Golang单元测试时能够更加顺利地进行,提高代码的质量和可靠性。

问题内容

我在尝试测试此函数时遇到问题,但内部有错误。以下是我的 responsejson 函数,它不返回错误,但发送响应 json。

func responsejson(w http.responsewriter, code int, message string) {
    jsonstatus := struct {
        code int `json:"code"`
        message string `json:"message"`
    }{
        message: message,
        code: code,
    }

    bs, err := json.marshal(jsonstatus);

    if err != nil {
        log.println("error in marshal json in responsejson: ", err)
        str := "internal server error. please contact the system administrator."
        io.writestring(w, str);
        return 
    } else {
        io.writestring(w, string(bs));
        return
    }
    
}

以下是我的单元测试代码,它创建了一个模拟 responsewriter,它能够成功测试编写器响应 json 的情况,没有错误。由于我没有在 responsejson() 函数中返回错误类型,因此如何在 test_responsejson 函数中测试它,如下所示?

func test_responsejson(t *testing.t) {
    responsejsontests := []struct {
        testname string
        code int
        message string
        expectedjsonresponse string
    } {
        {"successful login", http.statusok, "successfully logged in!", `{"code":200,"message":"successfully logged in!"}`},
        {"existing username", http.statusbadrequest, "username already exists. please try again.", `{"code":400,"message":"username already exists. please try again."}`},
    }

    for _, e := range responsejsontests {
        // creating a mock responsewriter
        w := httptest.newrecorder()

        responsejson(w, e.code, e.message)

        // read the response body as a string
        body, _ := io.readall(w.result().body)
        actual := string(body)

        expected := e.expectedjsonresponse
        if actual != expected {
            t.errorf("%s: expected %s but got %s", e.testname, e.expectedjsonresponse, actual)
        }
    }
}

此外,我还创建了一个函数,它为 log.println() 内置函数生成实际的日志输出。我知道 log.println() 函数是一个内置函数,它不太可能失败。但是,我希望在单元测试中实现 100% 的覆盖率。请帮忙!谢谢:)

func GenerateLogOutput(message string, errorMessage string) string {
    // Create a new bytes.Buffer to capture the log output
    var buf bytes.Buffer

    // Redirect log output to a different destination set as a buffer
    // By default, log message are written to the standard error stream os.Stderr
    log.SetOutput(&buf)

    // Generate an error
    err := errors.New(errorMessage)

    w := httptest.NewRecorder()

    // Calling the function
    InternalServerError(w, message, err)
    actualOutput := buf.String()

    return actualOutput
}

解决方法

简单地说,我们可以为 responsejson 函数编写一个测试用例,如下所示。

func Test_ResponseJson(t *testing.T) {
    tests := []struct {
        Code        int
        Message     string
        ExpectedStr string
    }{
        {
            Code:        1,
            Message:     "sample message",
            ExpectedStr: "{\"code\":1,\"message\":\"sample message\"}",
        },
    }
    for _, test := range tests {
        w := httptest.NewRecorder()

        ResponseJson(w, test.Code, test.Message)

        res := w.Result()
        data, err := ioutil.ReadAll(res.Body)
        res.Body.Close()

        actualStr := string(data)

        assert.Nil(t, err, "Invalid test data")
        assert.Equal(t, actualStr, test.ExpectedStr)
    }
}

我们无法从 bs 获取错误,err := json.marshal(jsonstatus)json.marshal 函数可以返回两种类型的错误。

  1. unsupportedtypeerror(例如:通道、复合值和函数值)
  2. unsupportedvalueerror(例如:循环数据结构)

我们无法解析值来生成上述错误之一。我们正在解析具有支持的值和支持的类型的结构。因此,我们无法编写 100% 覆盖率的测试。

以上是Golang 单元测试的简单错误问题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
使用GO编程语言构建可扩展系统使用GO编程语言构建可扩展系统Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳实践有效地使用Init功能的最佳实践Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函数在GO软件包中的执行顺序INIT函数在GO软件包中的执行顺序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

在GO中定义和使用自定义接口在GO中定义和使用自定义接口Apr 25, 2025 am 12:09 AM

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

在GO中使用接口进行模拟和测试在GO中使用接口进行模拟和测试Apr 25, 2025 am 12:07 AM

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在GO中使用init进行包装初始化在GO中使用init进行包装初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

GO的选择语句:多路复用并发操作GO的选择语句:多路复用并发操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高级并发技术:上下文和候补组GO中的高级并发技术:上下文和候补组Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines

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

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

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中