В следующем методе первый блок catch никогда не запускается, даже если выдается исключение типа ExceptionType:
/// <summary>
/// asserts that running the command given throws an exception.
/// </summary>
public static void Throws<ExceptionType>(ICommand cmd)
where ExceptionType : Exception
{
// Strangely, using 2 catch blocks on the code below makes the first catch block do nothing.
try
{
try
{
cmd.Execute();
}
catch (ExceptionType)
{
return;
}
}
catch (Exception f)
{
throw new AssertionException(cmd.ToString() + " threw an exception of type " + f.GetType() + ". Expected type was " + typeof(ExceptionType).Name + ".");
}
throw new AssertionException(cmd.ToString() + " failed to throw a " + typeof(ExceptionType).Name + ".");
}
как указано в следующем тесте:
[Test]
public void Test_Throws_CatchesSpecifiedException()
{
AssertThat.Throws<AssertionException>(
new FailureCommand()
);
}
используя следующий класс:
class FailureCommand : ICommand
{
public object Execute()
{
Assert.Fail();
return null; // never reached.
}
public override string ToString()
{
return "FailureCommand";
}
}
дает следующий вывод в NUnit:
TestUtil.Tests.AssertThatTests.Test_Throws_CatchesSpecifiedException:
FailureCommand выдал исключение типа NUnit.Framework.AssertionException. Ожидаемый тип: AssertionException.
Я также пытался использовать 2 блока catch для 1 блока try (вместо того, чтобы вкладывать try / catch во внешнюю попытку), но получил те же результаты.
Есть идеи, как перехватить исключение, указанное в качестве параметра типа в одном блоке перехвата, но перехватить все другие исключения в другом?