Unit-testing a simple collection class

前端 未结 3 736
故里飘歌
故里飘歌 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 07:01

    There are two possibilities.

    1. You've exposed a flaw in your design. You should carefully consider if the actions that your Add method is executing is clear to the consumer. If you don't want people adding duplicates to the list, why even have a Contains() method? The user is going to be confused when it's not added to the list and no error is thrown. Even worse, they might duplicate the functionality by writing the exact same code before they call .Add() on their list collection. Perhaps it should be removed, and replaced with an indexer? It's not clear from your list class that it's not meant to hold duplicates.

    2. The design is fine, and your public methods should rely on each other. This is normal, and there is no reason you can't test both methods. The more test cases you have, theoretically the better.

    As an example, say you have a functions that just calls down into other layers, which may already be unit tested. That doesn't mean you don't write unit tests for the function even if it's simply a wrapper.

提交回复
热议问题