1

I have MS Test unit tests that ensure that an Exception is thrown when the method under test is given bad arguments. I'm using the pattern:

My actual;
bool threw = false;
try
{
    actual = target.DoSomething(aBadParameter);
}
catch
{
    threw = true;
}

Assert.IsTrue(threw);

I have CLR Exceptions set to break only when user-unhandled (not when thrown). When DoSomething() throws a new Exception(), however, the debugger breaks. If I resume, the unit test completes successfully.

If I cut-and-paste the unit test code into the main program and run it in the context of the main program (instead of under MS Test), the debugger does not break at the user-handled Exception.

How can I prevent the debugger from breaking on my user-handled Exceptions?

This does not appear on the surface related to

Getting an Unhandled Exception in VS2010 debugger even though the exception IS handled

because in that case the Exception was being thrown on a different thread and was being rethrown by the CLR inside a callback.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553

1 Answers1

2

The idiomatic way to test for thrown exceptions in MSTest is using the ExpectedException attribute:

[TestMethod]
[ExpectedException(typeof(FooException))]
public void ThrowsFooExceptionWithBadInput()
{
     var actual = target.DoSomething(aBadParameter);
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • I was about to type this one in. +1 – Gregory A Beamer Feb 22 '12 at 22:31
  • I get exactly the same behavior with ExpectedException. See http://stackoverflow.com/questions/2628965/expectedexception-on-testmethod-visual-studio-2010 – Eric J. Feb 22 '12 at 22:34
  • @Eric J: Just noticed this might not address the main concern in your question - that the debugger breaks even though exception is handled. Let me know if this helps, otherwise will delete. – BrokenGlass Feb 22 '12 at 22:35
  • @EricJ.: Well you basically linked to the answer - what remains there to be said? – BrokenGlass Feb 22 '12 at 22:37
  • 1
    @BrokenGlass: The accepted answer did not work for me (I had previously tried that). However, one of the un-upvoted answers did solve my problem: Tools|Options|Debugging and un-check the "Enable Just My Code". Accepting because your answer got me back on the right path. – Eric J. Feb 22 '12 at 22:42