Sto solo cercando alcuni esempi di quando è opportuno utilizzare Assert.Catch o Assert.Throws per asserire eventuali eccezioni generate nelle unit test. So che posso usare ExpectedException, ma sono curioso di sapere la differenza tra "Catch" e "Throws" in particolare. Grazie!Quando utilizzare Assert.Catch versus Assert.Throws in Unit Test
6
A
risposta
9
La prima linea del documentation sembra abbastanza chiaro:
Assert.Catch
è simile aAssert.Throws
ma passerà un'eccezione derivata da quella specificata.
Quindi utilizzare Assert.Catch
se un'eccezione che deriva dal l'eccezione specificata è valida (il che significa che troppo sarebbe stato catturato in una catch
blocco equivalente).
La documentazione per Assert.Throws fornisce esempi di entrambi:
// Require an ApplicationException - derived types fail! Assert.Throws(typeof(ApplicationException), code); Assert.Throws<ApplicationException>()(code); // Allow both ApplicationException and any derived type Assert.Throws(Is.InstanceOf(typeof(ApplicationException), code); Assert.Throws(Is.InstanceOf<ApplicationException>;(), code); // Allow both ApplicationException and any derived type Assert.Catch<ApplicationException>(code); // Allow any kind of exception Assert.Catch(code);