mardi 26 février 2019

Testing datastructures with slices of complex types

I keep running into a problem where I have a complex data structure that has a slice of []Foo (where Foo is a complex struct) that can be accessed by a method Foos() []Foo, but then I want to consume this as a simpler interface (ex. []fmt.Stringer). However, even if foo implements fmt.Stringer, go can't use a []Foo as a []fmt.Stringer (even though it could use a Foo as a fmt.Stringer).

How can I write this in a testable way so I don't have to implement an entire mock Foo just to get fmt.Stringer functionality?

Simple example: `

type Foo struct {
    ...lots of fields...
}

... dozens of methods...

func (f Foo) String() string {
    return “this is foo”
}

type FooBox struct {
    ... lots of fields...
    foos []Foo
}

...dozens of methods...

func (fc FooBox) Foos() []Foo {
    return fc.foos
}

type fooBoxer interface {
    Foos() []fmt.Stringer
}

var _ fmt.Stringer = Foo{} // works
var _ fooBoxer = FooBox{} // does not compile, because the compiler can’t convert []Foo to []fmt.Stringer

`

Aucun commentaire:

Enregistrer un commentaire