使用目录测试失败

时间:2019-10-20 21:06:11

标签: 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);
}

1 个答案:

答案 0 :(得分:4)

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

//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...
}