Debugging Nunit tests in Visual Studio C# Express 2010 - c#

I've followed this advice to get debugging working for NUnit tests.
http://www.blackwasp.co.uk/NUnitCSharpExpress.aspx
However, i have several tests that do Assert.Throws<...>, which causes the debugger to break when the exception i'm testing for occurs, when really i want it to break if an exception occurs outside of those calls.
How can i get the debugger to ignore exceptions caused from within these kinds of methods?
EDIT: I've event tried the below, which doesn't work!
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
try
{
Assert.Throws<ArgumentNullException>(() => new CachedStreamingEnumerable<int>(null));
// This still throws and stops be being able to debug tests called after this one
}
catch
{
}
}

Here is what worked for me (although in Visual Studio Professional, not Express, but I guess that should not matter).
Bring up the "Exceptions" Dialog as suggested by Ninjapig.
Click on the Add... Button, to open the "New Exception" dialog.
Select "Common Language Runtime Exceptions" in the drop down box
In the Edit box enter "NUnit.Framework.AssertionException".
Click OK to close the "New Exception" dialog.
Back in the "Exceptions" dialog make sure that both checkboxes (Thrown and User-unhandled) are unchecked.
Now, the debugger should completely ignore a NUnit assertion failure (i.e. a thrown, caught or not, NUnit.Framework.AssertionException).
UPDATE: This will only prevent from breaking into the debugger, it cannot ignore the exception itself; i.e. it will not alter the actual program flow. Appart from changing or replacing or encapsulating the Assert-calls in try-catch blocks, I don't think there is anything that can achieve that (at least not automatically).

I'm uncertain if VS2010 Express has this option, but you can choose the exceptions to break on .
Go to the 'Debug' menu, then select 'Exceptions'
and from here you can select what exceptions to break on

I've ended up referencing nunit-gui-runner.dll and invoking it like
NUnit.Gui.AppEntry.Main(new string[] { Dll });
This brings up the NUnit gui. I can then run the specific test i'm interested in.

I had the same problem. Although your original approach (without the need for a try...catch block) works for most exception types, ArgumentNullException doesn't work. I fixed it like this:
[Test]
public void InstanciatingWithNullParameterThrowsException()
{
bool isArgumentNullExceptionThrown = false;
try
{
new CachedStreamingEnumerable<int>(null);
}
catch (ArgumentNullException)
{
isArgumentNullExceptionThrown = true;
}
Assert.That(isArgumentNullExceptionThrown);
}
It's not as elegant, but it does seem to work.

Related

How to prevent break on specific exception if it's handled

Normally I want the debugger to break on ArgumentOutOfRangeException.
But within my try catch(ArgumentOutOfRangeException) that exception is already handled and so I want the debugger to not break.
I tried the DebuggerStepThrough attribute, but it still breaks.
You can do this by setting the debugger to break on user unhandled exceptions.
Go to Debug -> Exceptions, Common Language Runtime Exceptions, de-tick (uncheck) the Thrown box. Of course you can get very precise with what you want to break on by drilling down into that list. Be aware that this setting takes effect across the whole solution, you can't set it per class or method. If you do want to be more selective per method, then consider using compile directives to not include that bit of code during debug time.
As for the DebuggerStepThrough attribute, that is to prevent breaking on break points, nothing to do with breaking on exceptions.
You should check your visual studio isn't set to break on all exceptions
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions,
for example, Common Language Runtime Exceptions.
Microsoft Visual Studio Help
There is a way. First disable debugging code that is not yours. Go to Tools > Options > Debugging > General > select "Enable Just My Code (Managed only)". Now tell the debugger that this one function is not part of your code with DebuggerNonUserCodeAttribute:
[System.Diagnostics.DebuggerNonUserCode()]
private void FunctionThatCatchesThrownException()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException ex)
{
//...
}
}
If an exception (some other than ArgumentOutOfRangeException) gets out of the function debugger will catch it as usual, but the location of interception will be where the function is called.

Windows Form Won't Display in Debug Mode

I recently upgraded to VS 2012. I have a set of coded UI tests that I've coded in VS 2010 and I'm trying to spin them up in VS 2012. I have a windows form that I'm displaying at the beginning of the test run by using the AssemblyInitialize attribute. I use this form to allow users to select from sets of values and those values are used to data feed the tests. Here's a copy of my code that displays the form:
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
ProcessUtility.TerminateAll();
if (!File.Exists(Directory.GetCurrentDirectory() + #"\RunInfo.ser"))
{
InitializeForm initForm = new InitializeForm();
initForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
initForm.ShowDialog();
}
}
So, here's my headache: the form displays just fine in Run mode. However, if I try to spin it up in Debug mode, it never displays. I've stepped through the code. It's loading all of the controls for the form with no errors. I make it to the 'initForm.ShowDialog()' line of code. It runs that line of code but then nothing happens. I don't receive any errors and the status in the lower left of the IDE is 'Ready'. It's almost as if the IDE thinks the form is displayed but it's not. I've double-checked the Task Manager and it's just not there. I've verified the build configuration is set to Debug. I've tried cleaning the solution and re-building. This code continues to work in VS 2010. Please tell me someone out there has ran into a similar problem because I'm out of ideas. I'm new to stackoverflow so let me know if there is anything else I can provide to better explain the issue. Thank you in advance for taking a look at it.
Not sure why this solution works, but I was able to solve this issue in VS2013 by setting the visible property on the form I was trying to display to true and then false before calling ShowDialog.
VB.Net example code
Dim form as Form = new Form
form.Visible = True
form.Visible = False
form.ShowDialog
I was able to get the form to display using the following code instead of ShowDialog. I still have no idea why ShowDialog wasn't working but this does the trick:
InitializeForm initForm = new InitializeForm();
initForm.Visible = true;
initForm.Focus();
Application.Run(initForm);
Most likely a exception is happening during the initialization, Go in to the Debug->Exceptions dropdown menu and be sure the checkbox thrown for Common Language Runtime Exceptions is checked, this will let your code break on the exception that is happening.
If you are still not catching the exception go to Debug->Option and Settings then uncheck the box for Enable Just My Code and check the box for Break when exceptions cross AppDomain or managed/native boundries
This may give you some "read herring" exceptions, as some .NET processes use exceptions for control of flow logic. So just be aware that the first exception you see may not be the cause of your problem.
I was experiencing the same thing while debugging an old code and resolved the situation by adding [STAThread] attribute on top of container method which contains form.ShowDialog();
For example:
[STAThread]
public void MessageBoxShow(string errorMessage)
{
using (frmError errorForm = new frmError(errorMessage))
{
errorForm.ShowDialog();
}
}
This has solved any hanging occured while hitting-continuing debug point.
Platform Windows 7 x64 enterprise edition and VS2008 (both has latest updates as of today).
Hope this helps.
Update 1: Please ignore using statement in example since I am using a custom form which inherits IDisposable in addition to Windows.Form and has custom disposition routines. Sorry if it has created any confusion.

Application hangs only when breakpoint is triggered, .NET, C#, Visual Studio

I refactored my application a while ago and since then I've been having problems with debugging using Visual Studio 2010.
My application works as expected while not debugging (not stepping through the application. An attached debugger does not cause any issues). However, when a breakpoint is triggered and I start to step through the app, Visual Studio and the app both hang after at most 3-4 steps.
To emphasize this point even more: It works well with my customers and regardless of whether I start it from Visual Studio or stand-alone - as long as no break point is triggered.
It does not matter where in the code I place the break point.
IDE: Visual Studio 2010 x64
Platform: .NET 4.0
The refactoring included a lot of cross-thread calls to BeginInvoke - all channeled through the following method:
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
There is not a single call to Control.Invoke() in the project.
Is there something wrong with the above method?
Additionally, I'd appreciate any hints on how you would track down this bug. My current approach is to add output to the console and selectively deactivating parts of the code.
I would suspect that in some cases the code you show poses a problem since InvokeRequired lies in case IsHandleCreated is false - it returns false even if you are not on the GUI thread.
For reference see http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx .
The following code throws an exception instead of hanging... the fact that it "works as expected" when no breakpoint is hit might be a result of the debugger freezing all threads on hitting a breakpoint which in turn might lead to a different order of execution etc.
Altogether this means: you might have some "race condition" in your code where BeginInvokeIfRequired is called on a freshly created control before that control has a Handle. This can even be some 3rd-party code you use...
public static void BeginInvokeIfRequired(this Control control, Action action)
{
if (control.IsHandleCreated)
{
if (control.InvokeRequired)
{
control.BeginInvoke(action);
}
else
{
action.Invoke();
}
}
else {
// in this case InvokeRequired might lie !
throw new Exception ( "InvokeRequired is possibly wrong in this case" );
}
}

Try-Catch unknown behaviour

I'm currently learning after a book about how to convert xaml code into objects during runtime.
I have the following code:
try
{
ctrl = XamlReader.Load(xaml) as UserControl;
}
catch (Exception exc)
{
OnXamlResult(new XamlCruncherEventArgs(exc.Message)); return;
}
The code is not mine, I took it from the book.
The problem is that try-catch does not work properly, or at least as I know till now.
During debugging the program stops when it reaches the line :
ctrl = XamlReader.Load(xaml) as UserControl;
without catching the exception.
What am I doing wrong or how can I solve this problem?
"xaml" is a string. It is taken from a textbox and if the xaml is correctly typed by the user the program should convert the xaml code into object otherwise it should display the corresponding error.
About how the program reacts, i can say that debug stops(it returns me to visual studio pointing the error) and it is not behaving like going into a infinite cycle.
It's probably the debugger breaking as the exception occurs. Stick a breakpoint inside the catch and F5 to continue, it should carry on and hit your breakpoint.
And by "breaking", I don't mean it fails, I mean it pauses execution of the app on the offending line of the exception, so it's a Good Thing in this instance.
If you are using Visual Studio, you can enable/disable this "break on exception" behaviour:
Debug -> Exceptions... (Ctrl + Alt + E)
Common Language Runtime Exceptions, check the boxes to the right as needed.
As for the exception itself, unless it's there specifically to show exceptions, it is likely having trouble loading the provided XAML string.

"The debugger cannot continue running the process."

I've been messing with VS 2010 debugging settings, trying to get stepping into the .NET Framework working. Well, I can't get it to work. I've also tried the Reflector VS plugin and that was working at one point.
Then I randomly started getting this error:
This only happens when I have a breakpoint on a line that calls IEnumerable<T>.ToList(). If I try to step-over or step-into on that line where my breakpoint is set, I get this error dialog and my debugging session ends.
If I move the breakpoint to the line below, the debugger makes it past the ToList() call!
I've tried the following to no avail:
Removing the Reflector plugin.
Undoing my changes in the Tools > Options > Debugging window (unchecked the option to step into the .NET Framework; unchecked the source server option; checked the just my code option).
Unchecked Microsoft Source Server in the Tools > Options > Debugging > Symbols window.
Cleared the symbol cache.
What is going on?
Because this was the first place I came to when I searched for an answer, I'll add what I found out.
In my case, I had the debugger set up in the solution to start multiple projects. For some reason this setting was changed by Visual Studio so that no project was starting. Correcting the setting in the solution immediately solved the problem.
The problem was not difficult to solve, but the error message was more than a bit irritating.
I've just found this answer useful. All I did was change my start-up project to another, and back to normal.
My project probably lost this setting somewhere, and resetting it made it available again.
It was a ToString() override that make the debugger crash ! (After the evaluation the debugger will show you the result with the ToString() method). And if you get an exception in the ToString(), you will never catch an exception because you cannot code them on the debugger behaviour.
I've got this answer from msdn
I suffered from same problem....
I found one solution which heard uncommon....
The debugger cannot continue running the process.Process was terminated
While debugging your code step by step , you will find the line , from where error redirecting.
If you are using " ToString() " anywhere in that file ,please remove that .
Instead of the ,you can use Value / Text .
It works fine.
............
If you were not used ToString() any where in program , then reload project copy by removing completely.
I had the same problem. I traced it down to a class(step-by-step debugging) and finally to a property(commenting all the code, then step-by-step uncommenting).
this property returned a typed dataSet from a table.Dataset
private typedDataSet myDataSet
{
return this.DataSet as typedDataSet;
}
this was in a DataTable partial class.
After I removed this property everything went OK.
I ran into this issue with a code bug from copy/paste. Instead of get/setting the private member variable, I did a get/set on itself. When I referenced the property in other code the debugger terminated (2010):
public bool ProdToDeve
{
get { return ProdToDeve; } // <= missing underbar
set { ProdToDeve = value; }
}
private bool _ProdToDeve = false;
This message will also show up when you're trying to debug a Xamarin solution but you have a class library selected as the startup project instead of your application porject.
It occurred to me when I was doing the following:
throw new Exception(timeout.TotalSeconds + " second(s)");
That's because timeout.TotalSeconds.ToString() which indeed is an override method for an object of type double, was throwing a Parameter not valid exception.
Finally, for safety I ended up doing the following:
throw new Exception(System.Convert.ToString(timeout.TotalSeconds));
Well, typically, this is also the kind of error message you can get in a multi-threads context. In brief, it involves concurrency : make sure that your resource accesses are always secured.
In my case, I got this error message when I forgot to secure resource accesses at some places within my code. To solve this issue, I just had to decorate the critical sections with a lock instruction (on the concerned resource). I hope this will help those who are in this context.

Categories

Resources