2

我有以下方法来测试,我已经编写了两个测试,测试抛出异常的场景,我想知道哪个是正确的。

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)是否包含某些内容,因此我不确定应该使用哪个。

任何意见将不胜感激。

谢谢

4

2 回答 2

2

首先,您不应该检查您是否将错误消息添加到列表中?

Assert.AreEqual(errorMessageList.Count, 1);

其次,虽然第二个测试不那么冗长,并且更具可读性(因为您不需要实现另一个类),但这并不重要- 这两个测试都是实现相同目标的有效方法。只需选择一个并继续您的下一个功能...

于 2012-07-27T19:01:40.180 回答
1

第二个测试看起来更好。我认为您IIOManager应该使用其他方法来维护第一个测试(更新存根),但对第二个测试不做任何事情。

about IOManager, FileSystem- 看起来更合适的类名

于 2012-07-27T20:03:33.560 回答