I have a void method that checks if a given path exists and if not creates it, it is contained in a FileServices class with an IFileServices corresponding interface
public interface IFileServices{
void CreateFolder(string path);
}
public class FileServices : IFileServices{
private readonly IDirectory _directory;
public FileServices(IDirectory directory){
_directory = directory;
}
public void CreateFolder(string path){
if(!_directory.Exists(path))
_directory.CreateDirectory(path)
}
}
I'm trying to test with Nunit and Moq where the passed path doesn't exist and then it is created
[Test]
public void TestDirectoryDontExistAndCreated()
{
var mockedDir = new Mock<IDirectory>();
mockedDir.Setup(s => s.Exists(It.IsAny<string>())).Returns(false);
mockedDir.Setup(s => s.CreateDirectory(It.IsAny<string>())).Callback((string path) => { Directory.CreateDirectory(path); });
var service = new FileServices(mockedDir);
service.CreateFolder("C:\\temp:\\testDir");
Assert.IsTrue(Directory.Exists("C:\\temp:\\testDir"));
}
my issues/questions are
- Assert is failing
- is there a better way to do this without using Directory class ?
- I thought about adding a new setup for s.Exists after the invocation of service.CreateFolder so it would return true for the passed value, would this be considered a good practice ? something like:
mockedDir.Setup(s => s.Exists("C:\\temp:\\testDir")).Returns(true);
CodePudding user response:
Instead of creating the folder using Directory
(and depending on it), you can validate if mock methods of IDirectory
were invoked or not. If those are invoked then you would be covering the CreateFolder
of FileServices
. Use Verify
of moq to validate the invocation of methods.
[Test]
public void TestDirectoryDontExistAndCreated()
{
var mockedDir = new Mock<IDirectory>();
mockedDir.Setup(s => s.Exists(It.IsAny<string>())).Returns(false);
mockedDir.Setup(s => s.CreateDirectory(It.IsAny<string>()));
var service = new FileServices(mockedDir);
// Asserts
mockedDir.Verify(mock => mock.Exists(It.IsAny<string>()), Times.Once());
mockedDir.Verify(mock => mock.CreateDirectory(It.IsAny<string>()), Times.Once());
}
With above approach, now you can also validate the scenario when directory exist (by validating the 0 invocation of CreateDirectory
method).