duande9301 2015-03-08 16:27
浏览 26
已采纳

去:测试不能通过?

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条回答 默认 最新

  • duanbaque4230 2015-03-08 17:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作