Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Approach for XDocument.Load() and XDocument.Save()

I am working with XDocument within an MVC4 Web API application in Visual Studio 2010 and am unsure about the testing strategy.

Most of my unit tests make use of an in memory XDocument, which works well for controller, service, repository tests.

However, I have the XDocument.Load(filename) and XDocument.Save(filename) scenarios, which I would like to test (either with unit or integration tests).

I have been looking at the following question\answer on SO here but I'm not sure how to proceed.

public class PathProvider
{
   public virtual string GetPath()
   {
      return HttpContext.Current.Server.MapPath("App_Data/policies.xml")
   }
}

PathProvider pathProvider = new PathProvider();
XDocument xdoc = XDocument.Load(pathProvider.GetPath());

So, I get that I can now mock calls to whatever calls XDocument.Load(pathProvider.GetPath()).

Should I then be trying to test that PathProvider works? If, so, How would I approach this?

Thanks

Davy

like image 317
davy Avatar asked Nov 04 '22 04:11

davy


1 Answers

Should I then be trying to test that PathProvider works? If, so, How would I approach this?

My answer is no, at least not with an automated test to begin with.

Simply due to the code snippet you provided, the PathProvider is an wrapper (adapter) around the ASP.NET framework. The only tests I would rely on here would be collaboration tests, e.g. I would verify that GetPath() is invoked when you expect it to be. That being said, context is key here.

PathProvider pathProvider = new PathProvider();
XDocument xdoc = XDocument.Load(pathProvider.GetPath());

The above code reeks of "testing the framework", therefore I would not even bother to unit test such code. If you really wanted to ensure that this portion of code did the right thing with the XML files and so forth, I'd fallback to an integration test. Though do consider this may be slow and brittle.

My solution therefore would be to abstract the concept of the XML document being loaded as you have with the PathProvider. From here, manual testing would suffice. Along the way if there is any domain logic included in such adapters, I would then extract classes/methods which you could test in isolation without the need to worry about XML or document loading etc...

like image 191
Finglas Avatar answered Nov 15 '22 12:11

Finglas