Go 为实现接口的对象创建可测试的示例
根据GoLang文档,您可以为一段代码编写示例。 有关更多信息,请参阅 我有以下方法:Go 为实现接口的对象创建可测试的示例,go,testing,Go,Testing,根据GoLang文档,您可以为一段代码编写示例。 有关更多信息,请参阅 我有以下方法: // 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)
// 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)
}
我想为这做一个可测试的例子,用以下代码完成:
// 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
}
这一切正常,测试正在执行中,但go-vet
向我发送了以下消息:
`ExampleWrite refers to unknown identifier: Write`
我应该如何命名我的示例方法,使其链接到函数
func(s StdOutSink)Write(msg message)
您是否阅读了您发布的链接中的“示例函数名称”部分?如果你根据这些建议重命名你的示例函数,你仍然会得到vet错误吗?我不敢相信我错过了那部分。它解决了这个问题。