用于 xml / 字符串测试失败的自定义 testify 输出

我正在使用 testify 测试 XML 封送处理,并strings.Contains用于检查我希望包含在 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 语句会很糟糕。关于清理这个更具可扩展性的任何想法?


千万里不及你
浏览 162回答 1
1回答

烙印99

除非格式很重要,否则测试诸如 xml.Marshal 之类的东西的快速彻底方法是对对象进行编组和比较func (suite *BookSuite) TestXMLMarshal() {&nbsp; &nbsp; priceXML, priceErr := xml.Marshal(PriceType{Price: 10, Type: "IND"})&nbsp; &nbsp; suite.Nil(priceErr)&nbsp; &nbsp; var secondPrice PriceType&nbsp; &nbsp; unerr :=&nbsp; xml.Unmarshal(priceXML, &secondPrice)&nbsp; &nbsp; suite.Nil(unerr)&nbsp; &nbsp; if !reflect.DeepEqual(&priceXML,&secondPrice){&nbsp; &nbsp; &nbsp; &nbsp; err := fmt.Errorf("Expected: '%+v'\nGot: %+v\n",priceXML,secondPrice)&nbsp; &nbsp; &nbsp; &nbsp; suite.Error(err, err.Error())&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; }}没有经过测试,但应该是这样的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go