我有一个类具有接收 xml 文件并从磁盘加载 xsd 文件以生成 html 代码的功能。
我想构建一个单元测试,测试它发送的 xml。
问题是单元测试和核心app在不同的文件夹下,所以main函数无法从磁盘加载xsd文件,因为相对路径不同。
最佳答案
您可以更改代码以便注入(inject) xsd。您还可以使用 MS Fakes 从您的测试代码中提供 xsd。
如果您使用 MS Fakes,伪代码的小示例可能如下所示:
public class SoftwareUnderTest()
{
private void ThisDoesSomethingWithXSD()
{
var fil = File.Open(ApplicationDirectory + "\myxsd.xsd");
}
}
[TestClass]
public class TestCode()
{
[TestMethod]
public void Test()
{
using (ShimsContext.Create())
{
// Arrange:
// Shim DateTime.Now to return a fixed date:
System.Fakes.ShimFile.Open =
() => { return File.Open("\\Testpath\text.xsd"); };
// Instantiate the component under test:
var sUT = new SoftwareUnderTest();
//ACT
//ToDo: write your testcode
//Assert
}
}
}
注入(inject)有点简单,如下所示,但它确实需要更改您的代码以允许测试,并且它使您的类的使用变得复杂:
public class SoftwareUnderTest(string xsdPath)
{
private void ThisDoesSomethingWithXSD()
{
var fil = File.Open(xsdPath);
}
}
[TestClass]
public class TestCode()
{
[TestMethod]
public void Test()
{
// Instantiate the component under test:
var sUT = new SoftwareUnderTest("\\Testpath\text.xsd");
//ACT
//ToDo: write your testcode
//Assert
}
}
}
关于c# - 如何管理需要加载文件的函数的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56490343/