Question

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!)

Was it helpful?

Solution

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.

OTHER TIPS

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().

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top