How to Capture the Exception Message From Assert.Throws in NUnit

In the past I’ve used:

[ExpectedException(typeof(CustomException), ExpectedMessage="blah blah blah")] 

to set an exception expectation and assert on the message. With the recent releases of NUnit I’ve finally transitioned all my code to use:

Assert.Throws<CustomException>(() => someType.someMethod(someValue));

or

Assert.Throws<CustomException>(someType.someMethod);

if the method has no parameters.

Only lately have I needed to capture the exception message and validate it. To do this you do the following:

var ex = Assert.Throws<CustomException>(() => someType.someMethod(someValue));

Assert.That(ex.Message, Is.EqualTo("expected message here"));

I am blogging about this because I keep forgetting how to capture the exception message. Hope it helps someone else.

Jason Meridth

jmeridth

My name is Jason Meridth. I am a continuously learning senior software developer/devops/team lead/development manager trying to not let best be the enemy of better. I reserve the right to change my mind upon obtaining more information. I am also the owner and principal software consultant at Meridth, LLC. If you have any software, hardward, networking, process, etc needs please don't hesitate to reach out to me.

Raspberry Pi Kubernetes Cluster - Part 2

Howdy again.Alright, my 8 port switch showed up so I was able to connect my raspberry 3B+ boards to my home network. I plugged it in wit...… Continue reading

Raspberry Pi Kubernetes Cluster - Part 1

Published on April 07, 2018

SSH - Too Many Authentication Failures

Published on March 28, 2018