vendredi 14 avril 2017

How to unit test private properties?

I'm pretty new to TDD and I have a hard time to understand how to test private members of the class (I know! It's private, shouldn't be tested - but please keep reading). We might have a public function which sets private property and other public function that returns "something" based on that private property.

Let me show you a basic example:

public class Cell
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Value { get; set; }
}

public class Table
{
    private Cell[,] Cells { get; }
    public Table(Cell[,] cells)
    {
        Cells = cells;
    }

    public void SetCell(int x, int y, string value)
    {
        Cells[x, y].Value = value;
    }

    public void Reset()
    {
        for (int i = 0; i < Cells.GetLength(0); i++)
        {
            for (int j = 0; j < Cells.GetLength(1); j++)
            {
                Cells[i, j].Value = "";
            }
        }
    }

    public bool AreNeighborCellsSet(int x, int y)
    {
        bool areNeighborCellsSet = false;

        // checking...

        return areNeighborCellsSet;
    }
}

In this example Cells are private, because there's no reason to make them private. I don't need to know what's the value of particular Cell outside this class. I just need an information if neighbor cells are empty.

1. How can I test Reset method?

Technically I should create a Table with mocked array of cells. Call Reset and then assert if every cell has empty Value. But I can't actually check if they are empty or not.

2. In this case I would call Assert many times (for every cell) - is it a good practice? I've read that "It's not!", but Reset resets all cells, so I have to somehow check every cell.

Aucun commentaire:

Enregistrer un commentaire