I have the following method to test and i have written two tests, testing the scenario that an exception is thrown, and im wondering which is correct.
namespace JimBob.CsvImporter.Entity
{
public interface IIOManager
{
Stream OpenFile(string path);
TextReader ReturnReader(string path);
}
public class IOManager : IIOManager
{
public Stream OpenFile(string path)
{
return File.Open(path, FileMode.Open);
}
public TextReader ReturnReader(string filePath)
{
return new StreamReader(filePath);
}
}
public class EntityVerification
{
private IIOManager _iomgr;
public EntityVerification(IIOManager ioManager)
{
this._iomgr = ioManager;
}
...
/// <summary>
/// Ensures user can open file.
/// </summary>
/// <param name="errorMessageList">A running list of all errors encountered.</param>
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);
}
}
Tests:
[Test]
public void ValidateAccessToFile_CanReadWriteToFile_ThrowException()
{
List<String> errorMessageList = new List<string>();
StubService stub = new StubService();
EntityVerification testObject = new EntityVerification(stub);
testObject.ValidateAccessToFile("ergesrg", errorMessageList);
Assert.AreEqual(errorMessageList.Count, 0);
}
[Test]
public void ValidateAccessToFile_CanReadWriteToFile_ThrowsException()
{
Mock<IIOManager> mock = new Mock<IIOManager>();
mock.Setup(x => x.ReturnReader(It.IsAny<string>())).Throws(new InvalidOperation("throw baby."));
EntityVerification testObject = new EntityVerification(mock.Object);
List<String> errorMessageList = new List<string>();
testObject.ValidateAccessToFile("blabla.txt", errorMessageList);
Assert.AreEqual(errorMessageList.Count, 0);
}
public class StubService : IIOManager
{
public Exception ex;
public Stream OpenFile(String path)
{
throw ex;
}
}
Both tests just check that a local variable, in this case errorMessageList, to the test contains something so im not sure which i should be using.
Any comments would be appreciated.
Thanks
First, shouldn’t you be checking that you do add an error message to the list?
Second, although the second one is a little less verbose, and more readable (as you don’t need to implement another class), it doesn’t matter – the two tests are both valid ways of achieving the same target. Just choose one and move on to your next feature…