Search code examples
gocompiler-errorstrace

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


Firstly I'm writing a package myself named trace and it has two files, to run the entire package I write to the terminal:

go test -cover

But this error comes out:

--- 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

Here is the code of the two files in the trace package: The first one, 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}
}

The second one, 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")
}

I'd really like someone to help me with this, I'm stuck. (I don't want the test to fail but to pass).


Solution

  • go cover runs tests and reports their success, in addition to producing coverage information. It seems like your options are to either ignore the FAIL message from the failing test, or remove the t.Error line that's causing the failure.

    A more complicated solution would be to add a flag (or build tag) that conditionally fails the incomplete test based on its value. Then you can set the flag when running go cover. But personally I wouldn't bother with anything so complicated.