views:

893

answers:

3

I truly love NUnit's new(er) ability to test for expected exception testing, ie:

var ex = Assert.Throws<SomeException>(()=>methodToThrowException("blah"));

One minor issue I find is that to test some sort of operator overload or other assignment type functionality, the only way I can know how to do this is by giving the compiler a variable to assign to, like so:

// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { var ignored = nbr / m; });

This is compact and works great, but has the annoyance where Resharper puts out a warning that the variable ignored is never used. This is counter productive if you like to use Resharper visuals to help you judge the quality of the code at a glance, as I do. Resharper is technically correct of course, but is there a way to tell Resharper this is my intention? I have a test with a lot of these sorts of tests, so a pragma will look nasty.

Any suggestions (besides "get over it, dude")?

Cheers

+4  A: 

You could write your own Throws method which takes a Func<object> instead, and then just write:

var ex = Assert.Throws<PreconditionException>(() => nbr / m);

Then submit the new method to NUnit and wait for the next release :)

Jon Skeet
+3  A: 

Add a field to the unit test and suppress the warning, ie:

// ReSharper disable UnaccessedField.Local
        private object _ignore;
// ReSharper restore UnaccessedField.Local

The use that field as the assignment variable in your test delegate:

// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { _ignore = nbr / m; });

This keeps resharper quiet, so you know if it does complain about something now it is likely a legitimate complaint that should be looked at. This eliminates the noise level so you can focus (I have over 50 tests like this in an important class that needs some refactoring).

Cheers, Berryl

Berryl
A: 

And it's really neat you can get the exception and work with it ...

var exception = Assert.Throws<ArgumentException>(() => dlinvalid.ProcessData());
Assert.That(exception.Message, Is.EqualTo("foo bar"), "Expected bar foo");

Plus it works with Resharper, whereas ExpectedException seems to be failing with NUnit 2.5

SteveC