I have a standard table-test unit-test in Go. How can I make it simpler, easy to read and succinct?
I'm looking suggestions for: Structural refactoring. Less and simple code to achieve the same thing.
test.go
func Test_Parses_Books(t *testing.T) {
books := xmlDoc.Book
type tester struct {
texts []Text
bookID int
categoryLen int
}
getBookTest := func(i int) tester {
book := books[i]
return tester{
texts: book.BookNames,
bookID: book.BookID,
categoryLen: len(book.Categories),
}
}
booklen := len(books)
if booklen != 4 {
t.Errorf("expected: 4. got: %d", booklen)
}
var testTable = []struct {
expected tester
actual tester
}{{
expected: tester{
texts: []Text{
{"BOOK", "TV"},
{"en", "TV"}},
bookID: 1,
categoryLen: 2},
actual: getBookTest(0),
}, {
expected: tester{
texts: []Text{
{"BOOK", "PS4"},
{"en", "PS4"}},
bookID: 5,
categoryLen: 2},
actual: getBookTest(1),
}, {
expected: tester{
texts: []Text{
{"BOOK", "XBOX"},
{"en", "XBOX"}},
bookID: 22,
categoryLen: 1},
actual: getBookTest(2),
}, {
expected: tester{
texts: []Text{
{"BOOK", "PS3"},
{"en", "PS3"}},
bookID: 17,
categoryLen: 1},
actual: getBookTest(3),
}}
for i, test := range testTable {
if !reflect.DeepEqual(test.expected, test.actual) {
t.Errorf("\nexpected: [%d]\n\t%#v.\ngot:\n\t%#v",
i, test.expected, test.actual)
}
}
}