For example take the following class:
class GameBoard
{
public double Evaluate(PieceType cpusPieceType)
{
...
for (var i = 0; i < _tableRepository.Size; ++i)
for (var j = 0; j < _tableRepository.Size; ++j)
if (_tableRepository [i, j] != PieceType.Empty)
{
var isMax = _tableRepository [i, j] == cpusPieceType;
var value = EvaluatePosition (i, j, _tableRepository [i, j]);
...
}
...
}
protected virtual double EvaluatePosition (int row, int column, PieceType pieceType)
{ ... }
}
I would like to write a test for Evaluate function but this in turn depends on the values returned by EvaluatePosition function which is declared protected. Now, my idea was that I could use a class like:
class XGameBoard : GameBoard
{
protected override double EvaluatePosition (int row, int column, PieceType pieceType)
{
// this will call EvaluatePosition_ShouldReturn which will be mocked and have a value previously set up
return EvaluatePosition_ShouldReturn (row, column, pieceType);
}
public virtual double EvaluatePosition_ShouldReturn (int row, int column, PieceType pieceType)
{
return base.EvaluatePosition (row, column, pieceType);
}
}
The test would look like this:
_gameBoardMock = new Mock<XGameBoard>(...);
for (var i = 4; i < _size - 4; i += 2)
for (var j = 4; j < _size - 4; j += 2)
_gameBoardMock.Setup (x => x.EvaluatePosition_ShouldReturn (i, j, PieceType.Cross)).Returns (1.0);
var result = _gameBoardMock.Object.Evaluate (PieceType.Cross);
The problem is that EvaluatePosition inside the Evaluate function always returns 0, and not the overriden function is invoked which should return the value that was set up.
Thanks in advance.
I would like to clarify the problem a little more. The situation is that the Evaluate function should return a double value based on some logic and the returned values of the EvaluatePosition function. Basically, the Evaluate function depends on the values returned by EvaluatePosition function, but the function has to be tested in isolation so I had to create a stub for the EvaluatePosition function and mimic the return values by setting up those initially. My approach seems to be usable the only thing that is needed is the following statement:
Because the EvaluatePosition function is declated protected the values that it should return cannot be set up by Moq, therefore I created the XGameBoard class that declares the EvaluatePosition_ShouldReturn function which is public and usable by Moq and this way I can set up the values that the normal EvaluatePosition function should return:
Because the EvaluatePosition function is overriden in the XGameBoard class, when this function is invoked it will invoke the EvaluatePosition_ShouldReturn function whose values are set up by Moq and should return the specified values.
I hope that some may find this approach useful for unit testing. Happy coding.