1

我知道单元测试应该与任何依赖项隔离。我正在尝试使用 Typemock 为应用程序编写单元测试。问题是类中的方法之一接受几个 Xml 文件路径参数,然后在方法内创建一个 XMLDocument 对象,以便在方法的某处使用。

 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;
 }

如何为此编写单元测试而无需指定物理位置?注意:不幸的是,我不允许更改代码。

4

3 回答 3

3

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.

于 2012-04-17T09:16:22.927 回答
1

您始终可以创建一个临时 Xml 并传递临时文件的路径,然后在执行测试后将其删除。在 NUnit 中,这可以使用[SetUp][TearDown]属性轻松完成。

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

于 2012-04-17T09:04:19.523 回答
1

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.

于 2012-04-17T09:19:42.353 回答