我在通过此测试时遇到问题。问题是,Write()我的结构中的方法需要写入一个属性,但io.Writer接口不接受指针作为其接收者。
filelogger.go:
package logger
import (
"io"
)
type FileLogger struct{
File io.Writer
}
func NewFileLogger(file io.Writer) *FileLogger{
return &FileLogger{file}
}
func (this *FileLogger) Log(message string) error {
_, err := this.File.Write([]byte(appendNewLine(message)))
return err
}
filelogger_test.go:
package logger
import (
"testing"
"github.com/stretchr/testify/assert"
)
type WriterMock struct{
data []byte
}
func (this WriterMock) Write(b []byte) (n int, err error) {
this.data = append(this.data, b ...)
return len(this.data), nil
}
func NewMockedFileLogger() *FileLogger{
writer := WriterMock{}
fileLogger := FileLogger{writer}
return &fileLogger
}
func TestLog(t *testing.T) {
fileLogger := NewMockedFileLogger()
fileLogger.Log("Hello World!")
assert.Equal(t, "Hello World!", string(fileLogger.File.(WriterMock).data))
}
测试输出:
--- FAIL: TestLog (0.00 seconds)
Location: filelogger_test.go:32
Error: Not equal: "Hello World!" (expected)
!= "" (actual)
FAIL
正如我提到的,data []byte没有被写入,因为我不能将函数接收器设置为指针,因为它不会满足io.Writer.
慕斯709654
相关分类