I have the following method
public void ValidateAccessToFile(string filePath, List<String> errorMessageList)
{
try
{
using (FileStream fs = (FileStream)_iomgr.OpenFile(filePath))
{
if (fs.CanRead && fs.CanWrite) { }
else
{
errorMessageList.Add("Can not read/write to the specified file.");
}
}
}
catch (Exception e)
{
errorMessageList.Add(e.Message);
}
}
and id like to test that it writes to the “errorMessageList” if either of the properties, CanRead or CanWrite are false. Is this possible?
[Test]
public void ValidateAccessToFile_CanReadWriteToFile_NoErrorAddedToErrorListMessage()
{
Mock<IIOManager> mock = new Mock<IIOManager>();
mock.Setup(x => x.OpenFile(It.IsAny<string>())).Returns(new MemoryStream());
List<String> errorMessageList = new List<string>();
VerificationManager testObject = new VerificationManager(mock.Object);
testObject.ValidateAccessToFile("Random.txt", errorMessageList);
Assert.AreEqual(errorMessageList.Count, 0);
}
How can i assign a value to the New MemoryStream properties?
Thanks for your time.
EDIT
Below is the final test method i wrote.
public void ValidateAccessToFile_CanReadWriteToFile_NoErrorAddedToErrorListMessage()
{
bool _isReadOnly = true;
List<String> errorMessageList = new List<string>();
Mock<IIOManager> mock = new Mock<IIOManager>();
mock
.Setup(x => x.IsReadOnly(It.IsAny<string>()))
.Returns(_isReadOnly);
VerificationManager testObject = new VerificationManager(mock.Object);
testObject.ValidateAccessToFile(It.IsAny<string>(), errorMessageList);
Assert.AreEqual(errorMessageList.Count, 0);
}
According to the documentation for
MemoryStream.CanRead, the property will always returntrueas long as the stream is open. (CanWriteis less clear, but I believe it is the same.)So, you can close the stream before returning it, or you can mock a
Streamwith the appropriate overrides.Incidentally, I’m not sure that a
MemoryStreamcan be casted into aFileStream. See this post.