views:

116

answers:

2

To test that something throws for example an ArgumentException I can do this:

Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));

How can I check that the ParamName is correct in a clear way? And bonus question: Or would you perhaps perhaps recommend not testing this at all?

+3  A: 

If you want to do more with the exception than just assert that it is thrown, then Assert.Throws actually returns the exception and you can do this:

var exception = Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));
// Assert something else about the exception
David M
That message is just the message that will be displayed if the assertion fails?
Svish
NUnit, `Assert.Throws<T>` assertion method returns the exception.
João Angelo
@João - thanks, edited answer.
David M
@Svish - thanks also. I'm having a bad day.
David M
Ah, of course you come with this while I write mine :p Will accept this then, unless someone else comes up with something even better :)
Svish
Accept your own - there's a special badge for that isn't there? ;)
David M
hm, I don't know? :p Either way I have to wait 48 hours, so... hehe
Svish
+5  A: 

Found a pretty clear way (but please let me know if anyone have an even better one!)

var e = Assert.Throws<ArgumentException>(() => dog.BarkAt(deafDog));
Assert.That(e.ParamName, Is.EqualTo("otherDog"));

Facepalm...

Svish
This is my preferred approach.
Programming Hero
Assert.IsTrue(e.ParamName=="otherDog") ? :)
alexm
@alexm: But using that would create a less obvious message when the test fails: *Expected string length 4 but was 7. Strings differ at index 0. Expected: "otherDog" But was: "somethingElse"* vs *Expected: True But was: False*. ;)
Svish