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
.