Struggling with go today.. second question I've had to ask.
I've got 2 tests that test a write function Write()
, that takes writer io.WriterAt
and content interface{}
.
I'm working with (2) tests written for the function, TestWriteSuccessful
and TestWriteFail
.
The error I'm getting for both functions when testing is:
cannot use &b (type *bytes.Buffer) as type io.WriterAt in argument to Write:
Question
What does implement WriterAt that I can replace bytes.Buffer with in these tests to make the tests functional?
What I've tried
- Changing
b
's type toos.File
- theb.len() > 0
fails then. - Extensively googled how to test io.WriterAt and functions implementing it, only thing I found was that bytes.Buffer does NOT implement an io.WriterAt, only io.Writer, but no further information.
- Checked the godocs, I see that io.WriterAt calls
WriteAt
and takes a slice of bytes and an offset:WriteAt(p []byte, off int64) (n int, err error)
, and I see that bytes.Buffer can be used to callWrite
, but no information aboutWriteAt
Code
Write function:
func Write(writer io.WriterAt, content interface{}) error {
data, err := json.Marshal(content)
if err != nil {
return err
}
writer.WriteAt(data, 0)
return nil
}
Tests for Write function (test imports Testify):
func TestWriteSuccessful(t *testing.T) {
var b bytes.Buffer
err := Write(&b, exampleSystemConfig)
assert.Nil(t, err)
assert.True(t, b.Len() > 0)
}
func TestWriteFail(t *testing.T) {
var b bytes.Buffer
err := Write(&b, make(chan int)) // Write will return UnsupportedTypeError
assert.NotNil(t, err)
}
Expected result
Both tests succeed.
Actual result
internal/platform/store/store_test.go:33:15: cannot use &b (type *bytes.Buffer) as type io.WriterAt in argument to Write:
*bytes.Buffer does not implement io.WriterAt (missing WriteAt method)
internal/platform/store/store_test.go:40:15: cannot use &b (type *bytes.Buffer) as type io.WriterAt in argument to Write:
*bytes.Buffer does not implement io.WriterAt (missing WriteAt method)