c# - 使用目录测试失败

标签 c# nunit moq

我的测试失败了。 GetFiles 方法返回的集合为空,不知道为什么。

这是我的:

public class FileNamesProvider : IFileNamesProvider
{
    private readonly IDirectory _directoryWrapper;
    private readonly IReadOnlyList<string> _fileNames;

    public FileNamesProvider(IDirectory directoryWrapper)
    {
        _directoryWrapper = directoryWrapper;

        var folder = GetFolderOfExecutingAssembly();

        _fileNames = GetFileNamesFromPatternFilesFolder(folder);
    }

    public IReadOnlyList<string> GetFileNamesForPatternFiles() => _fileNames;

    private string GetFolderOfExecutingAssembly() =>
        new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new InvalidOperationException()).LocalPath;

    private IReadOnlyList<string> GetFileNamesFromPatternFilesFolder(string folder) => _directoryWrapper.GetFiles($"{folder}\\patterns", "*.txt");
}

还有我的测试:

[TestFixture]
public class FileNamesProviderTests
{
    private Mock<IDirectory> _fakeDirectoryWrapper;

    [SetUp]
    public void SetUp()
    {
        _fakeDirectoryWrapper = new Mock<IDirectory>();
    }

    [Test]
    public void GetFileNamesForPatternFiles_ReturnsExpectedFileNamesInCorrectCollectionType()
    {
        //Arrange
        var fileNamesProvider = new FileNamesProvider(_fakeDirectoryWrapper.Object);
        _fakeDirectoryWrapper.Setup(_ => _.GetFiles(It.IsAny<string>(), It.IsAny<string>()))
            .Returns(new[] { "a.txt", "b.txt" });

        //Act
        var result = fileNamesProvider.GetFileNamesForPatternFiles();

        //Assert
        Assert.AreEqual(new[] { "a.txt", "b.txt" }, result);
        Assert.That(result.GetType() == typeof(IReadOnlyList<string>));
    }
}

这是包装器:

public class DirectoryWrapper : IDirectory
{
    public DirectoryWrapper()
    {
    }

    public string[] GetFiles(string path, string searchPattern) => Directory.GetFiles(path, searchPattern);
}

最佳答案

在创建模拟对象的实例之前移动设置:

//setup
_fakeDirectoryWrapper.Setup(_ => _.GetFiles(It.IsAny<string>(), It.IsAny<string>()))
                     .Returns(new[] { "a.txt", "b.txt" });
//then create mocked object
var fileNamesProvider = new FileNamesProvider(_fakeDirectoryWrapper.Object);

你真的应该在 SetUp 方法中执行任何模拟方法/属性/事件的设置,然后你可以从实际的单元测试中删除它:

[SetUp]
public void SetUp()
{
    _fakeDirectoryWrapper = new Mock<IDirectory>();

    // setup GetFiles
    _fakeDirectoryWrapper.Setup(_ => _.GetFiles(It.IsAny<string>(), It.IsAny<string>()))
                         .Returns(new[] { "a.txt", "b.txt" });

    // setup any other methods...
}

关于c# - 使用目录测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477334/

相关文章:

c# - 在 NUnit 测试中使用最小起订量模拟 HttpContext.Current

msbuild - 是否可以知道 ReSharper 的测试运行程序何时构建我的项目?

c# - 如何使用 Nunit 断言每个集合项

c# - 如何在 ListView 元素中显示图像?

c# - 是否可以使用 Moq 从实例中获取模拟实例?

c# - 使用 Moq 将参数修改为 stub void 方法

c# - 设置 Mock 以重定向到重载方法

c# - 如果字符串非空则添加到字符串

c# - 在 Win7 32 位上使用 Gtk# 进行国际化

c# - 远程调用时 Powershell SendKeys 访问被拒绝