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:
What does implement WriterAt that I can replace bytes.Buffer with in these tests to make the tests functional?
b
's type to os.File
- the b.len() > 0
fails then.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 call Write
, but no information about WriteAt
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)
}
Both tests succeed.
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)
It's easy enough to make your own WriterAt
for testing purposes — it's any type that implements a WriteAt
function with the correct signature. If you're only interested in knowing the number of bytes written, it can be as simple as
type TestWriter struct {
BytesWritten int
}
func (tw *TestWriter) WriteAt(b []byte, _ int64) (n int, err error) {
tw.BytesWritten += len(b)
return len(b), nil
}
then you can test with
func TestWriteSuccessful(t *testing.T) {
var tw TestWriter
err := Write(&tw, exampleSystemConfig)
assert.Nil(t, err)
assert.True(t, tw.BytesWritten > 0)
}
func TestWriteFail(t *testing.T) {
var tw bytes.Buffer
err := Write(&tw, make(chan int)) // Write will return UnsupportedTypeError
assert.NotNil(t, err)
}