登录
首页 >  Golang >  Go问答

无法构建Go测试:调用可能包含格式指令

来源:stackoverflow

时间:2024-02-23 10:03:30 277浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《无法构建Go测试:调用可能包含格式指令》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

当对库中要测试的函数的调用按设计包含格式化指令时,go test 拒绝构建。这是故意的还是错误?不管怎样,有解决方法吗?

请注意,与 call 有可能的格式化指令不同,这不是对不接受格式化指令的内置函数的调用。它是对我编写的函数的调用,该函数是专门为接受格式化指令而设计的。

这是一个人为但完整的复制品。注意 makeerror 旨在处理格式字符串。 go build 工作正常,但 go test 会产生以下错误并且不运行任何测试:

.\example.go:16:13: makeerror call has possible formatting directive %v
fail    sandbox/example [build failed]

go版本:go版本go1.12.7 windows/amd64

example.go

package example

import "fmt"

type errexample struct {
    data interface{}
    msg  string
}

func (e *errexample) error() string {
    return e.msg
}

func divide(f1 float64, f2 float64) (float64, error) {
    if f2 == 0.0 {
        return 0, makeerror(nil, "cannot divide %v by 0", f1)
    }
    return f1 / f2, nil
}

func makeerror(data interface{}, msgandargs ...interface{}) error {
    msg := ""
    switch len(msgandargs) {
    case 0:
        // ignore
    case 1:
        msg = fmt.sprint(msgandargs[0])
    default:
        if str, ok := msgandargs[0].(string); ok {
            msg = fmt.sprintf(str, msgandargs[1:]...)
        }
        msg = fmt.sprint(msgandargs...)
    }
    return &errexample{data: data, msg: msg}
}

example_test.go

package example

import (
    "testing"
)

func TestDivide(t *testing.T) {
    _, err := Divide(1230, 0)
    if err == nil {
        t.Errorf("Expected error when dividing by 0")
    }
}

解决方案


摘自go test的帮助文本:

终于介绍完啦!小伙伴们,这篇关于《无法构建Go测试:调用可能包含格式指令》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>