如何使此类可以进行单元测试?

时间:2019-03-04 18:48:25

标签: c# unit-testing oop

我有一个实现专用缓冲区类型集合的类。 在我看来,例如Flush方法不是可单元测试的。如果我想测试添加数据后会发生什么,请刷新它,再次添加数据,然后再次刷新它,看看我是否只取回第一次刷新后添加的数据。为了使我能够做到这一点,我也必须使用Add方法。在测试中使用另一种方法属于被测类的一部分,应该单独进行单元测试是一种不好的做法吗?此类甚至可以进行单元测试吗?诸如此类的问题会弹出,我无法回答。预先感谢!

public class DataBuffer : IDataBuffer
{
    private Dictionary<string, List<Dictionary<string, object>>> buffer;

    public DataBuffer()
    {
        buffer = new Dictionary<string, List<Dictionary<string, object>>>();
    }

    public void Add(string type, Dictionary<string, object> data)
    {
        if (!buffer.ContainsKey(type))
        {
            buffer[type] = new List<Dictionary<string, object>>();
        }
        buffer[type].Add(metrics);
    }

    public Dictionary<string, List<Dictionary<string, object>>> Flush()
    {
        var result = buffer;
        buffer = new Dictionary<string, List<Dictionary<string, object>>>();

        return result;
    }

    public int Count(string type) => buffer[type].Count;
}

基本上,我想编写这样的单元测试。这看似有效吗?

    [TestMethod]
    public void Flush_NoDataIsGivenBackTwice()
    {
        var data1 = new Dictionary<string, object>
        { 
            { "key1", "value1" } 
        };
        dataBuffer.Add("type", data1);

        var result1 = dataBuffer.Flush();

        Assert.AreEqual(1, result1["type"].Count);
        Assert.AreSame(data1, result1["type"].First());

        var data2 = new Dictionary<string, object>
        {
            { "key2", "value2" }
        };
        dataBuffer.Add("type", data2);

        var result2 = dataBuffer.Flush();

        Assert.AreEqual(1, result2["type"].Count);
        Assert.AreSame(data2, result2["type"].First());
    }

1 个答案:

答案 0 :(得分:1)

我不明白为什么此类不应该易于测试。我想我想在一些实现选择上挑战您。

为什么要在创建新实例之前还清当前事务状态? 我认为Flush() / Clear()方法应该是无效的。

为什么不只在基础缓冲区上应用Clear()并将字段设置为只读?

为什么您在Count(string type)上不那么防御?我认为应该做这样的事情:

public int Count(string type)
{
    if(buffer.TryGet(type, out List<Dictionary<string, object>> subset)
    {
        return subset.Count;
    }
    return 0;
 }

我也希望在TryGet()方法中使用Add()

相关问题