Having trouble getting NUnit's Assert.Throws to work properly

Dave picture Dave · Mar 5, 2010 · Viewed 7.7k times · Source

I could have sworn that I've used NUnit's Assert.Throws to determine whether or not a particular exception gets thrown from a method, but my memory has failed me before. I read this post here on SO, but it didn't answer my question, as I know the correct syntax, and I don't want to do anything with the exception that gets returned (I don't want to look at the Exception's members, though this could be useful down the road).

I wrote unit tests to prove my lack of understanding in the use of Dictionary, and couldn't get it handle the KeyNotFoundException that gets thrown. Instead of NUnit catching it and passing the test, I get an unhandled KeyNotFoundException error when I run. I verified that I don't have the VS IDE set up to break on thrown .NET exceptions.

I've tried this two ways:

Assert.Throws( typeof(KeyNotFoundException), () => value = prefs["doesn't exist"]);

and

Assert.Throws<KeyNotFoundException>( () => value = prefs["doesn't exist"]);

but both result in an unhandled exception. What am I missing here?

UPDATE seems like others can't reproduce this. Here's a screenshot:

alt text

Answer

Ed Hastings picture Ed Hastings · Apr 22, 2011

This is an old thread, but try turning off Enable Just My Code in Visual Studio under Tools->Options. With that on, the debugger is trying to be helpful and stops at the last possible point within your code before the exception gets swallowed.

Or, at least that's my understanding of it.

If you turn off Enable Just My Code, the Assert.Throws should work correctly.