I usually don’t use ExpectedExceptionit unless I can force the exception to be thrown into one statement, or if other tests guarantee that the previous statements do not throw an exception.
: , . , ExpectedException , , , , - , , , .
, ( ), :
try
{
OperationThatShouldFail();
Assert.Fail("Expected exception");
}
catch (DataAccessException)
{
// Expected (no need for an assertion though)
}
( ExpectedException - , .)
. (, , ) , ExpectedException, . try/catch .
, , .
EDIT: , , , , , . teardown, ( ).
EDIT: ExpectedException (, , ) , , :
static void ExpectException<T>(Action action)
where T : Exception
{
try
{
action();
Assert.Fail("Expected exception " + typeof(T));
}
catch (T)
{
}
}
( ) , , , # 3. :
public void NHibernateRepositoryBaseDelete()
{
ExpectException<DataAccessException>(() =>
DeleteHelper(myOrder, myOrder.OrderId));
ExpectException<DataAccessException>(() =>
DeleteHelper(myOrderDetail, myOrderDetail.OrderDetailId));
ExpectException<DataAccessException>(() =>
DeleteHelper(mySchedule, mySchedule.ScheduleId));
}