views:

565

answers:

3

Is it possible for SelectNodes() called on an XmlDocument to return null?

My predicament is that I am trying to reach 100% unit test code coverage; ReSharper tells me that I need to guard against a null return from the SelectNodes() method, but I can see no way that an XmlDocument can return null (and therefore, no way to test my guard clause and reach 100% unit test coverage!)

+2  A: 

Is it necessary to reach 100% code coverage? Indeed, is it even possible under normal (i.e. controllable, testable) circumstances?

We often find that using "syntactic sugar" constructions like the using {} block, there are "hidden" code paths created (most likely finally {} or catch {} blocks) that can't be exercised unless some environmental condition (like a broken socket or broken disk) gets in the way.

Jeremy McGee
+4  A: 

Looking at Reflector, the SelectNodes() method on XmlDocument's base class, XmlNode, can return null if its attempt to create a navigator returns null. CreateNavigator() is pretty complex and will indeed return null under a few circumstances. Those circumstances appear to be around a malformed XML document - so there's your test case for failure of SelectNodes().

Jesse C. Slicer
Won't a malformed document fail to parse entirely? What I saw inside CreateNavigator seemed to deal only with valid markup
rpetrich
I think CreateNavigator() returns `null` but only for certain types of XmlNode (not including XmlDocument). So as far as I can see, if you have loaded an XmlDocument and it didn't throw when parsing, then CreateNavigator() will never return `null` and therefore SelectNodes() will never return `null`
Daniel Fortunov
+2  A: 

If you are calling SelectNodes on the XmlDocument itself and it really is an XmlDocument and not a derived class than SelectNodes won't return null.

If you create a descendant class and override the CreateNavigator(XmlNode) method then SelectNodes could return null.

Similarly, if you call SelectNodes on an EntityReference, DocumentType or XmlDeclaration node, you'll get null as well

In short, for 100% coverage on an XmlDocument or XmlNode you didn't just create, you have to test for null.

rpetrich
That's the problem: I *did* just create it, therefore I know in my heart that SelectNodes() can never return null. Though technically it *could*, say, if a later refactoring causes the document to be passed in externally. Only problem is that now I have no way to test the ==null case in a unit test.
Daniel Fortunov