Il blocco precedente che fa riferimento ad un'altra domanda + risposta su SO NON contiene una risposta corretta che si applica qui!È un'eccezione generica supportata all'interno di un fermo?
Ho un metodo utilizzato per il test dell'unità. Lo scopo di questo metodo è garantire che una parte di codice (a cui fa riferimento un delegato) genererà un'eccezione specifica. Se viene lanciata quell'eccezione, il test dell'unità ha esito positivo. Se non viene lanciata alcuna eccezione o viene lanciata un'altra eccezione di tipo, il test dell'unità fallirà.
/// <summary>
/// Checks to make sure that the action throws a exception of type TException.
/// </summary>
/// <typeparam name="TException">The type of exception expected.</typeparam>
/// <param name="action">The code to execute which is expected to generate the exception.</param>
public static void Throws<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch (TException)
{
return;
}
catch (Exception ex)
{
Assert.Fail("Wrong exception was thrown. Exception of type " + ex.GetType() + " was thrown, exception of type " + typeof(TException) + " was expected.");
}
Assert.Fail("No exception was thrown. Exception of type " + typeof(TException) + " was expected.");
}
La chiamata successiva dovrebbe riuscire, ma non riesce:
int result = 0;
Throws<DivideByZeroException>(() => result = result/result);
Quando viene generata l'eccezione prevista di tipo TException
, è sempre catturato dalla seconda cattura, non per la prima cattura. Perchè è questo?
Ovviamente posso utilizzare un workarround con una cattura e verificare se ex
è di tipo TException
. Voglio semplicemente sapere/capire perché questo codice viene compilato ma semplice (mai?) Funziona.
EDIT
Su richiesta di un "lavoro" demo:
using System;
namespace GenericExceptionDemo
{
class Program
{
static void Main(string[] args)
{
int n = 0;
Catch<DivideByZeroException>(() => n = n/n);
}
static public void Catch<TException>(Action action)
where TException: Exception
{
try
{
action();
Console.WriteLine("No exception thrown. !!!Fail!!!");
}
catch (TException)
{
Console.WriteLine("Expected exception thrown. PASS!");
}
catch(Exception ex)
{
Console.WriteLine("An unexpected exception of type " + ex.GetType() + " thrown. !!!FAIL!!!");
}
}
}
}
Quale framework di test dell'unità stai utilizzando? La maggior parte già ha 'Assert.Throws' ... –
Il tuo codice funziona per me ... per favore mostra un programma breve ma completo che mostri il problema. –
Perché affermare che viene lanciato un tipo sbagliato di eccezione? Forse. Lo stesso framework Net ti lancia un System.Drawing.Exception quando lavori con le GUI? –