Add Assert.Throws<TEx>( Func<object> ) for properties testing

Bug #958770 reported by Yuri Astrakhan on 2012-03-18
This bug affects 1 person
Affects Status Importance Assigned to Milestone
NUnit Framework
Charlie Poole

Bug Description

Sometimes an object is in a state that causes reading its properties to throw exception. For example, an object might be disposed, and will throw InvalidOperationException().

To test for such behavior, one would write

    var obj = CreateDisposedObject();
#pragma warning disable 168
    // Assuming Name cannot be accessed after disposing
    Assert.Throws<InvalidOperationException>(() => { var v = obj.Name; });
#pragma warning restore 168

Having pragmas and a temp variable is clearly inconvenient, and instead can be remedied with this overload:

    public static T Throws<T>(Func<object> code) where T : Exception
     return Assert.Throws<T>(() => { var v = code(); });

As a result, our code can now be written as:

    var obj = CreateDisposedObject();
    Assert.Throws<InvalidOperationException>(() => obj.Name);

Much more concise and self evident.

Thank you!

summary: - Add Assert.Throws( Func<T> ) for properties
+ Add Assert.Throws<TEx>( Func<object> ) for properties testing
description: updated
description: updated
Vitalii Maklai (vmcl) wrote :

I would prefer something like:

public static TException Throws<TException, T>(Func<T> action)
    where TException : Exception
    return Assert.Throws<TException>(() => { var v = action(); });

Changed in nunitv2:
status: New → Triaged
importance: Undecided → Wishlist
Changed in nunitv2:
assignee: nobody → Charlie Poole (charlie.poole)
affects: nunitv2 → nunit-3.0
tags: added: framework
To post a comment you must log in.
This report contains Public information  Edit
Everyone can see this information.

Other bug subscribers