As I get it, since the Exception is thrown in the parent, the message is as it is defined in parent - null (System.Exception: "Exception_WasThrown"
, message: "Exception of type 'System.Exception' was thrown."). How to work around this issue?
Program, roughly:
internal abstract class Figure
{
protected string BadFigExceptionMessage { get; set; }
public Figure(params int[] measurements)
{
if (measurements.Any(x => x<=0)) throw new Exception(BadFigExceptionMessage);
}
}
class Triangle : Figure
{
public Triangle(params int[] sides) : base(sides)
{
BadFigExceptionMessage = "Such a triangle does not exist.";
}
}
My test with NUnit:
[Test]
[TestCase(-2, -2, -6)]
[TestCase(0, 0, 0)]
public void CalculateSquareOf_ImpossibleTriagSides_ReturnExceptionNoSuchTriag(int a, int b, int c)
{
Exception ex = Assert.Throws<Exception>(() =>
SquareCalculatorLib.Calculator.CalculateSquareOf(a, b, c)); //involves the Triangle constructor
Assert.That(ex.Message, Is.EqualTo("Such a triangle does not exist."));
}
CodePudding user response:
Injecting the exception message into the constructor is one way to do this:
internal abstract class Figure
{
public Figure(string exMsg, params int[] measurements)
{
if (measurements.Any(x => x <= 0)) throw new Exception(exMsg);
}
}
class Triangle : Figure
{
public Triangle(int a, int b, int c) : base("Such a triangle does not exist.", a, b ,c) { }
}