开发者

XAttribute implementing IComparable during tests, but not when live

I have some code below that is throwing an exception in integration environments but not in my unit tests. Basically I'm sorting some XML elements (linq-2-sql XElement) by an attribute value. All the nodes have the attribute defined.

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

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

The exception thrown is "At least one object must implement IComparable". The code can be fixed to work in either case with:

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

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

But I wonder why does this throw an exception when ran in a debug environment, but not from my unit tests? I'm afraid some utilties my test libra开发者_开发技巧ry uses are having unexpected side effects, but I can't find anything. What should I look for?

Note that in the test environment, elements.First().Attribute("name") is not null but elements.First().Attribute("name") as IComparable is null, so in both cases the XAttribute does not implement IComparable.


No matter the environment XAttribute does not implement IComparable so you've already found the workaround by using .Value. Now if you are curuous as to why this exception occurs here's a test case: in your unit test you have an element with name attribute which is empty:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜