I know that the unit test should be isolated from any dependencies. I am trying to write unit tests for an application using Typemock. Issue is one of the methods in a class accepts a couple of Xml filepath parameters and then creates an XMLDocument object inside the method to be used somewhere in the method.

 public bool ValidateXml(String aFilePath, String ruleXmlPath)
 {
     XmlDocument myValidatedXml = new XmlDocument();
     try
     {
         myValidatedXml.Load(aFilePath);
     }
     catch
     {
         return false;
     }


     XmlDocument myRuleXml = new XmlDocument();
     try
     {
         myRuleXml.Load(ruleXmlPath);
     }
     catch
     {
         return false;
     }

     MyClass myObject = new MyClass(myValidatedXml);
     //Do something more with myObject.

     XmlNodeList rules = myRuleXml.SelectNodes("//rule");
     //Do something more with rules object.

     return true;
 }

How do I write a unit test for this without having to specify the physical location? Note: I am not allowed to change the code unfortunately.

有帮助吗?

解决方案

You could always create a temp Xml and pass the path of the temp file and then delete it after the Test is executed. In NUnit this can be easily accomplished using [SetUp] and [TearDown] attributes.

[TestFixture]
public class MyTest 
{
    private string tempPathXML;

    [SetUp]
    public void SetUp()
    {
        //Create XML file 
        // Save it in a temp path
    }

    [TearDown]
    public void TearDown()
    {
        //Delete the temp file
    }

    public void SampleTestForValidateXml()
    {
        //Test using tempPathXML
    }
}

the Setup method is executed before each test case and the Teardown method is executed after each test case

Note: For MSTest the [Setup] and [TearDown] attribute can be replaced with [TestInitialize] and [TestCleanup] respectively. Thanks Cwan !

其他提示

AB Kolan's suggestion is fine as a workaround. You could also have a set of test XML files in your test project and pass the paths to those files to your tested method in your tests.

However, let me make a general note that dependencies on file system should be isolated in the same fashoin as the dependencies on a database. In the case like yours I usually load a XML document from a stream or from a byte array that are provided by some kind of FileManager : IFileManager. This file manager encapsulates the file system operations.

You should refactor, so You pass an XmlDocument. Or even better; a wrapper - let's call it XmlDocWrapper -- that encapsulates the XmlDocuments functionality. The wrapper can have an interface - IXmlDocWrapper. If you pass the interface, you can mock it when you want to test your class.

If you do it in this way, you leave the file system out of the equation which is ALWAYS good in unit tests.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top