c# - 如何管理需要加载文件的函数的单元测试

标签 c# testing nunit

我有一个类具有接收 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/

相关文章:

testing - nodejs,文件更改时自动运行测试

nunit - 有什么是我在 NUnit 中可以做但在 MSTest 中不能做的吗?

c# - Assert.AreEqual - Null 与空字符串

c++ - 将 gcov 与子进程和共享库一起使用时没有覆盖

c# - 有没有办法从 C# 检查 SSRS 报告服务器是否正在运行?

c# - 在 .NET C# 中将动态对象转换为具体对象

c# - CredentialCache.Add 方法中的 authType 参数

testing - TestCafe 不在文本输入字段中写入

unit-testing - Silverlight 单元测试(使用 NUnit)

c# - 为什么有 "using namespace"然后是 "using namespace.class"