A coworker and I were working on a feature that required manipulating XML through the .NET XML DOM. Per our standard operating procedure, we were using test-driven development. We were updating an existing piece of code to do something different so we were working within an existing design that made use of direct calls to the XMLDocument object.

We went through a few iterations of red, green, refactor and finally arrived at an implementation that should have worked. Our test had an instance of XMLDocument that was creating nodes that we were sending into the code. But the code had its own XMLDocument that it was using to build the final XML structure. We kept getting an error with the message "The node to be inserted is from a different document context."

After searching around, we eventually found that the XMLDocument is very selfish in which nodes it allows to be added. If you attempt to add a node within an instance of XMLDocument that was not the originating instance of that node, you will receive the same error.

The solution in our case was to pull the XMLDocument instance creation out of the piece of code under test and pass it in as a modifiable parameter.