Search code examples
c#.netunit-testingtypemock

How to write Unit Test for a method that accepts an xml filepath as a parameter


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.


Solution

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