首页 > 解决方案 > 测试函数不返回值

问题描述

我正在对这个 Go 文件进行测试。我很困惑为什么它在工作时遇到问题。

func TestMy(t *testing.T) {
    arr := map[string]string{
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
        RandomOwner(): RandomString(9),
    }
    ds := DataSourceStr{
        data: arr,
    }

    for k, v := range ds.data {
        //create dataset in datasource value method
        res, err := ds.Value(k)
        fmt.Println(res)
        if err != nil {
            t.Errorf("%T does not implement Value method correctly, key %v not found", ds, k)
        }
        if res != v {
            t.Errorf("%T does not implement Value correctly. Expected %v but recieved %v: %v", ds, v, res, err)
        }
        return res, err
    }
} 

它为上面的函数返回 this 作为错误,

/home/incompleteness_hewlbern/Documents/Code_Projects/Tests/nearmap/Private_test_golang/datasource/datasource_test.go:64:3: too many arguments to return
    have (interface {}, error)
    want ()

我犯了什么错误,我应该在函数中设置类型吗?我如何简单地在函数内部打印东西来测试发生了什么(它似乎没有显示在控制台中)。

标签: go

解决方案


测试函数不返回任何内容,测试通过或失败(不符合预期)在这种情况下t.Errorf()用于向由go test ....

https://golang.org/pkg/testing/

在您的示例函数中,签名为不返回任何内容:func TestMy(t *testing.T) {但尝试返回(interface {}, error)因此错误。更改循环的最后一行return res, errreturn满足测试功能的签名并提前失败或完全删除该行(取决于所需的测试逻辑)将解决问题。


推荐阅读