jeudi 29 août 2019

Create testable examples for objects that implements interfaces

According to the GoLang document, you can write examples for a piece of code. See https://blog.golang.org/examples for more information.

I have the following method:

// StdOutSink is a 'log.Sink' implementation which logs to 'StdOut'.
type StdOutSink struct {
}

// Write prints a message to 'StdOut'.
func (s StdOutSink) Write(msg message) {
    fMsg := fmtMsg(msg)

    fmt.Printf("%v\n", fMsg)
}

And I would like to make a testable example for this, which is done with the following code:

// Ensures the correct implementation of the 'Write' method.
func ExampleWrite() {
    // Arrange.
    s := new(StdOutSink)

    // Act.
    s.Write(createMessage(traceS, "Message"))
    s.Write(createMessage(debugS, "Message"))
    s.Write(createMessage(infoS, "Message"))
    s.Write(createMessage(warnS, "Message"))
    s.Write(createMessage(errorS, "Message"))
    s.Write(createMessage(fatalS, "Message"))

    // Output:
    // [TRACE]: Message
    // [DEBUG]: Message
    // [INFO]: Message
    // [WARNING]: Message
    // [ERROR]: Message
    // [FATAL]: Message
}

// PRIVATE: createMessage returns a 'log.message' with the given severity and text.
func createMessage(s severity, txt string) message {
    msg := new(message)
    msg.severity = s
    msg.text = txt

    return *msg
}

This all works, the tests are being executed, but go-vet is given me the following message:

`ExampleWrite refers to unknown identifier: Write`

How should I name my example method so that it's linked to the function func (s StdOutSink) Write(msg message)

Aucun commentaire:

Enregistrer un commentaire