I have a test for a parseFruitXML function which returns the unmarshalled struct as ‘got’ and uses !reflect.DeepEqual to compare this against a populated struct called ‘want’.
The test reads a fruit.xml file as input to the function.
When fruit.xml is unmarshalled, this rule comes into play on the Cherries field,
“If the XML element contains character data, that data is accumulated
in the first struct field that has tag “,chardata”. The struct field
may have type []byte or string. If there is no such field, the
character data is discarded.”
(https://pkg.go.dev/encoding/xml#Unmarshal)
How do I handle the whitespace coming from the sample xml files in the ‘got’ for these tests? Do I add a Cherries field in the ‘want’ struct with the same amount of whitespace, or use strings.TrimSpace() on the Text field of ‘got’, or some other approach?
Example code:
fruit.xml
<fruit>
<apples>10</apples>
<oranges>20</oranges>
</fruit>
fruit_test.go
package fruit_test
import (
"encoding/xml"
"io"
"os"
"reflect"
"testing"
)
type Fruits struct {
XMLName xml.Name `xml:"fruit"`
Cherries string `xml:",chardata"`
Apples int `xml:"apples"`
Oranges int `xml:"oranges"`
}
func parseFruitXML(fruitResponse []byte) (Fruits, error) {
f := Fruits{}
if err := xml.Unmarshal(fruitResponse, &f); err != nil {
return Fruits{}, err
}
return f, nil
}
func TestFruit(t *testing.T) {
fruits, err := os.Open("fruit.xml")
if err != nil {
t.Fatalf("error opening fruit xml: %v", err)
}
defer func() {
_ = fruits.Close()
}()
b, err := io.ReadAll(fruits)
if err != nil {
t.Fatal(err)
}
want := Fruits{
XMLName: xml.Name{
Local: "fruit",
},
Apples: 10,
Oranges: 20,
}
got, _ := parseFruitXML(b)
if !reflect.DeepEqual(got, want) {
t.Errorf("got %+vn, want %+v", got, want)
}
}
4