0

I'm testing XML marshaling with testify and using strings.Contains to check if lines I expect to be included in the XML are in fact there.

However, I want to diff the actual vs. desired xml.

Currently, my code looks something like:

func (suite *BookSuite) TestXMLMarshal() {
    priceXML, priceErr := xml.Marshal(PriceType{Price: 10, Type: "IND"})

    suite.Nil(priceErr)
    linePresent := strings.Contains(string(priceXML), `<PriceType Price="10" Type="IND"></PriceType>`)

    if true != linePresent {
        err := errors.New("Expected: \n" + `<PriceType Price="10" Type="IND"></PriceType>` + "\nGot: \n" + bookString)
        suite.Error(err, err.Error())
        fmt.Println(err)
    }
}

There are more lines in the xml file than the single one in the test, so as you can imagine that if statement is going to be gross. Any ideas on cleaning this up that's more scalable?

daino3
  • 4,386
  • 37
  • 48

1 Answers1

1

Unless the formatting matters a whole bunch, a quick thorough way to test something like xml.Marshal is to marshal to and from and compare the objects

func (suite *BookSuite) TestXMLMarshal() {

    priceXML, priceErr := xml.Marshal(PriceType{Price: 10, Type: "IND"})

    suite.Nil(priceErr)

    var secondPrice PriceType
    unerr :=  xml.Unmarshal(priceXML, &secondPrice)
    suite.Nil(unerr)

    if !reflect.DeepEqual(&priceXML,&secondPrice){
        err := fmt.Errorf("Expected: '%+v'\nGot: %+v\n",priceXML,secondPrice)
        suite.Error(err, err.Error())
        fmt.Println(err)
    }
}

not tested but should be something like that.

matt.s
  • 1,698
  • 1
  • 20
  • 29
  • Thanks Matt. But we do want to test the actual format of the XML because it's being consumed by a 3rd party that specs the xml format (we have to jump through some hoops). Any ideas how to incorporate that? – daino3 Apr 12 '16 at 18:22
  • Unless there are some weird whitespace requirements, I would do the above and then do a xml prettyprint/canonicalization on the xml output. Most xml consuming apps don't care about whitespace (since the xml libary level logic usually handles that). If you need more control encoding/xml has Encoder.Indent to control whitespace that is output. – matt.s Apr 12 '16 at 18:32