Go: Test cannot pass?

风格不统一 提交于 2019-12-10 12:33:28

问题


I'm having a problem making this test pass. The problem is, the Write() method in my struct needs to write to a property, but io.Writer interface does not accept pointer as its receiver.

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

Test Output:

--- FAIL: TestLog (0.00 seconds)
        Location:       filelogger_test.go:32
    Error:      Not equal: "Hello World!" (expected)
                    != "" (actual)

FAIL

As I mentioned, the data []byte is not being written to, because I cannot set the function receiver as a pointer, as it won't satisfty the io.Writer.


回答1:


If you keep using a pointer to WriterMock, it should work:

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

Then:

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

I missed:

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

You need to call Write() on a pointer receiver, not a value receiver.
Since everything is passed by value in Go, using a value receiver would make a copy of the WriterMock instance.



来源:https://stackoverflow.com/questions/28928870/go-test-cannot-pass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!