xml / 字符串测试失败的自定义证明输出

Custom testify output for failing test of xml / strings

我正在使用 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 语句会很糟糕。关于清理它的更具可扩展性的任何想法?

除非格式很重要,否则测试 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)
    }
}

未测试,但应该是这样的。