我试图测试我用 Go 编写的代码,但我一直收到此错误,我不知道为什么

I tried to test my code written in Go but I keep getting this error and I don't know why

首先,我自己编写了一个名为 trace 的包,它有两个文件, 运行 我写到终端的整个包:

go test -cover

但是出现这个错误:

--- FAIL: TestNew (0.00s)
    tracer_test.go:19: We haven't written our test yet
FAIL
coverage: 100.0% of statements
exit status 1
FAIL    gizmo/go/src/trace      0.172s

这里是trace包中两个文件的代码: 第一个,tracer.go

package trace

import (
    "io"
    "fmt"
)

//Tracer is the interface that describes an object capable of tracing events throughout code

type Tracer interface {
    Trace(...interface{})
}


type tracer struct {
    out io.Writer
}

func (t *tracer) Trace(a ...interface{}){
    fmt.Fprint(t.out, a...)
    fmt.Fprintln(t.out)
}

func New(w io.Writer) Tracer {
    return &tracer{out: w}
}

第二个,tracer_test.go

package trace

import (
    "testing"
    "bytes"
)

func TestNew(t *testing.T) {
    var buf bytes.Buffer
    tracer := New(&buf)
    if tracer == nil {
        t.Error("Return from New should not be nil")
    } else {
        tracer.Trace("Hello trace package.")
        if buf.String() != "Hello trace package.\n" {
            t.Errorf("Trace should not write '%s'.", buf.String())
        }
    }
    t.Error("We haven't written our test yet")
}

我真的很想有人帮我解决这个问题,我被困住了。 (我不希望测试失败而是通过)

go cover 除了生成覆盖率信息外,还运行测试并报告其成功。似乎您的选择是忽略来自失败测试的 FAIL 消息,或者删除导致失败的 t.Error 行。

一个更复杂的解决方案是添加一个标志(或构建标签),根据其值有条件地使不完整的测试失败。然后就可以在运行go cover的时候设置flag了。但就我个人而言,我不会为任何如此复杂的事情烦恼。