【问题标题】:XAttribute implementing IComparable during tests, but not when liveXAttribute 在测试期间实现 IComparable,但在实时时不实现
【发布时间】:2010-03-25 23:02:17
【问题描述】:

下面有一些代码在集成环境中引发异常,但在我的单元测试中却没有。基本上,我正在按属性值对一些 XML 元素(linq-2-sql XElement)进行排序。所有节点都定义了属性。

IEnumerable<XElement> elements = ...; // elementes are of the form<recipe name="something">

elements.OrderBy(e => e.Attribute("name"))

抛出的异常是“至少一个对象必须实现 IComparable”。可以通过以下方式修复代码以在任何一种情况下工作:

IEnumerable<XElement> elements = ...; // elementes are of the form<recipe name="something">

elements.OrderBy(e => e.Attribute("name").Value)

但是我想知道为什么在调试环境中运行时会抛出异常,而不是来自我的单元测试?恐怕我的测试库使用的一些实用程序会产生意想不到的副作用,但我找不到任何东西。我应该寻找什么?

请注意,在测试环境中,elements.First().Attribute("name") 不为 null,但 elements.First().Attribute("name") as IComparable 为 null,因此在这两种情况下 XAttribute 都不实现 IComparable。

【问题讨论】:

    标签: linq-to-xml icomparable xattribute


    【解决方案1】:

    无论环境如何,XAttribute 都没有实现IComparable,所以您已经找到了使用.Value 的解决方法。现在,如果您对为什么会发生此异常感到好奇,这里有一个测试用例:在您的单元测试中,您有一个带有 name 属性的元素,它是空的:

    var elements = new[] { 
        new XElement("el1", new XAttribute("name", "foo")),
        new XElement("el1", new XAttribute("name", ""))
    };
    
    // This will throw the exception you are observing in your unit test
    var orderedElements = elements.OrderBy(x => x.Attribute("name")).ToArray();
    

    【讨论】:

    • 在抛出异常的情况下,我验证了 x.Attribute("name") 没有评估为 null。添加 x.Attribute("name").Value 没有引发异常的事实也表明 null 不是问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多