Reputation: 490
My test is failing. The returned collection returned from GetFiles
method is empty and I don't know why.
Here's my class:
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");
}
And my test:
[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>));
}
}
Here's the wrapper:
public class DirectoryWrapper : IDirectory
{
public DirectoryWrapper()
{
}
public string[] GetFiles(string path, string searchPattern) => Directory.GetFiles(path, searchPattern);
}
Upvotes: 1
Views: 78
Reputation: 16701
Move the setup before you create the instance of the mocked object:
//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);
You should really perform any setup of mocked methods/properties/events within the SetUp
method and then you can remove it from the actual unit test:
[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...
}
Upvotes: 4