去:测试不能通过?

时间:2015-03-08 16:27:30

标签: go tdd

我在测试通过时遇到了问题。问题是,我的struct中的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

1 个答案:

答案 0 :(得分:1)

如果你继续使用指针WriterMock,它应该有效:

func NewMockedFileLogger() *FileLogger{
    writer := &WriterMock{}
    fileLogger := FileLogger{writer}
    return &fileLogger
}

然后:

 assert.Equal(t, "Hello World!", string(fileLogger.File.(*WriterMock).data))

我错过了:

func (this *WriterMock) Write(b []byte) (n int, err error) {
...
}

您需要在指针接收器上调用Write(),而不是值接收器 由于所有内容都通过Go中的值传递,因此使用值接收器将生成WriterMock实例的副本