英文:
Custom testify output for failing test of xml / strings
问题
我正在测试使用testify进行XML编组,并使用strings.Contains
来检查我期望包含在XML中的行是否实际存在。
然而,我想要对实际的XML和期望的XML进行差异比较。
目前,我的代码大致如下:
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)
}
}
XML文件中的行比测试中的单个行要多,所以你可以想象,这个if语句会变得很冗长。有没有什么更可扩展的方法来简化这个问题呢?
英文:
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?
答案1
得分: 1
除非格式很重要,否则测试类似xml.Marshal的方法的一种快速而彻底的方法是将对象进行编组和解组,并进行比较。
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)
}
}
未经测试,但应该是这样的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论