據我了解,由于在父級中引發了例外,因此訊息與在父級中定義的一樣 - null(System.Exception: "Exception_WasThrown",訊息:“引發了'System.Exception'型別的例外。”)。如何解決這個問題?
程式,大致:
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.";
}
}
我對 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."));
}
uj5u.com熱心網友回復:
將例外訊息注入建構式是一種方法:
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) { }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468873.html
下一篇:如何以特定概率遍歷串列?
