Unit-testing a simple collection class

前端 未结 3 729
故里飘歌
故里飘歌 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

    Your test seems perfectly OK to me. You may have misunderstood a principle of unit testing.

    A single test should (ideally) only test one thing, that is true, but that does not mean that it should test only one method; rather it should only test one behaviour (an invariant, adherence to a certain business rule, etc.) .

    Your test tests the behaviour "if you add to a new set, it is no longer empty", which is a single behaviour :-).

    To address your other points:

    • Theoretically, there could be a bug in both, that only manifests in scenarios where they are not called one after the other.
      True, but that just means you need more tests :-). For example, add two numbers, then call Contains, or call Contains without Add.

    • An alternative approach might suggest mocking out or exposing (possibly using InternalsVisibleTo) the private _list member and have the test inspect it directly, but that could potentially create test maintainability problems[...]
      Very true, so don't do this. A unit test should always be against the public interface of the unit under test. That's why it's called a unit test, and not a "messing around inside a unit"-test ;-).

提交回复
热议问题