views:

64

answers:

1

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 library 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.

A: 

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();
Darin Dimitrov
In the case where the exception was thrown, I verified that x.Attribute("name") did not evaluate to null. The fact that adding x.Attribute("name").Value did not throw an exception also demonstrates that a null was not the problem.
Frank Schwieterman