I have an abstract class Shape
and a couple of classes inheriting from it (Square
, Rectangle
, Triangle
, Circle
, ...). I also have an AreaCalculator
class, which contains a method named CalculateAreasByShape()
. This method calls a series of CalculateShapeAreas<TShape>(List<TShape> shapes)
methods for each Shape
type.
Now, in my unit tests, I have the following code:
...
var areaMock = new Mock<AreaCalculator>(MockBehavior.Strict);
areaMock.Setup(m => m.CalculateAreasByShape()).Returns(new Dictionary<Type, decimal>());
var canvas = new DemoCanvas(shapes, perimeterMock.Object, areaMock.object);
var result = canvas.RunShapeCalculations();
...
This code fails on the fact, that MockBehavior
is set to Strict
and there is no setup for the CalculateShapeAreas<TShape>()
methods. Now, I know I could run a setup for each of the Shape types, e.g.:
areaMock.Setup(m => m.CalculateShapeAreas<Triangle>(It.IsAny<List<Triangle>>())).Returns(default(decimal));
But this will create a lot of duplicate code. I wonder whether we can use the fact that all shapes inherit from the same base class. I have tried the following, but it does not work:
areaMock.Setup(m => m.CalculateShapeAreas<Shape>(It.IsAny<List<Shape>>())).Returns(default(decimal));
Alternatively, is it possible to set MockBehavior.Loose
on a single generic method (meaning, it would not check the actual type)?
>())).Returns(default(decimal));` where in fact the first `Moq.AnyType` could be inferred. But what if the type needs _constraints_?