Unit-testing a simple collection class

前端 未结 3 731
故里飘歌
故里飘歌 2021-02-10 06:13

Consider the following class:

public class MyIntSet
{
    private List _list = new List();

    public void Add(int num)
    {
        if (         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-10 06:59

    In practice, your current test is fine. For something this simple it's very unlikely that bugs in add() and contains() would mutually conspire to hide each other. In cases where you are really concerned about testing add() and add() alone, one solution is to make your _list variable available to your unit test code.

    [TestClass]
    public void Add_AddOneNumber_SetContainsAddedNumber() {
        MyIntSet set = new MyIntSet();
        set.add(0);
        Assert.IsTrue(set._list.Contains(0));
    }
    

    Doing this has two drawbacks. One: it requires access to the private _list variable, which is a little complex in C# (I recommend the reflection technique). Two: it makes your test code dependent on the actual implementation of your Set implementation, which means you'll have to modify the test if you ever change the implementation. I'd never do this for something as simple as a collections class, but in some cases it may be useful.

提交回复
热议问题