我有以下方法来测试,我已经编写了两个测试,测试抛出异常的场景,我想知道哪个是正确的。
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);
}
}
测试:
[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;
}
}
两个测试都只是检查测试的局部变量(在本例中为 errorMessageList)是否包含某些内容,因此我不确定应该使用哪个。
任何意见将不胜感激。
谢谢