I'm trying to create some scenarios for unit testing purposes and running into some problems when dealing with complex objects that I'd like to start from a base state.
In the below example is a simplified case where we have a query builder that may take three parameters. In this case we must always supply all three parameters to avoid a NPE when trying to access a reference.
package main
import (
"fmt"
)
type Searcher struct {
Param string
}
type CompleteSearcher struct {
A *Searcher
B *Searcher
C *Searcher
}
func (c *CompleteSearcher) FormatQuery() string {
return fmt.Sprintf("%s%s%s", c.A.Param, c.B.Param, c.C.Param)
}
func main() {
testCases := []struct {
scenario string
want string
searcher *CompleteSearcher
}{
{
scenario: "A populated",
want: "A",
searcher: &CompleteSearcher{
A: &Searcher{Param: "A"},
B: &Searcher{},
C: &Searcher{},
},
},
}
for _, tc := range testCases {
got := tc.searcher.FormatQuery()
if got != tc.want {
fmt.Println("error")
}
}
}
My specific problem with this is mostly that the scenario must initialize all fields creating a noisy test where it's somewhat unclear what's actually under test. You can imagine with even more searchable fields, cache classes, backend classes, etc. that a simple enough function can have an enormous object responsible for actually doing the setup.
So what I'd like to do instead is something like the following.
baseSearcher := &CompleteSearcher{
A: &Searcher{},
B: &Searcher{},
C: &Searcher{},
}
testCases := []struct {
scenario string
want string
searcher *CompleteSearcher
}{
{
scenario: "A populated",
want: "A",
searcher: New(baseSearcher){A: &Searcher{Param: "A"}}
},
}
Essentially I'd like to be able to test an entire object, but have the option to start with a "base" version of that object to prevent repeated setup in each scenario setup. From what I can tell there's no way to create a copy (even a shallow-copy) and then also do another assignment in a single statement, making it effectively impossible to have each scenario handle the object directly.
Any tips on how to resolve this issue?