How to test C# code without running an application

One thing that I love about scripting languages is that, to test some code you do not need to create a sample application and run that application. You can simple run the interpreter, write the code you want to test and you get the results… With compiled languages this is harder to achieve.

So whenever I need to test something, like for example let’s say I want to test what the .ToString() would give me for a DateTime object I need to create a sample application, write my code, compile and run… Quite cumbersome to test some simple code!

Enter TestDriven.Net

TestDriven.Net is a brilliant tool! This tool is a VS plugin to run Unit tests. Long story short, to run a unit test you need to right click in the Test method and Select “Run Test(s)” (shown in the image below). You also have the option to run the test with the debugger. This feature enables you to have breakpoints in your code and step through your test (to do this you must select the “Test with Debugger” option from the context menu).

TestDriven

Now how does TestDriven.Net fit in this article?

TestDriven.Net can be used to not only run tests but also normal code (at the end of the data, a test is still C# code). So basically if you are writing a method and you want to run some code all you have to do is to put a breakpoint inside you method, right click and select Test with Debugger and voila you are now running the code you wanted without the need to start the whole application or even worse create a sample application!

Once you are in debug mode, you can use the Immediate window to write whatever code you want to test and it will get evaluated there and then. You can also change the values of the variables that are in context from the Immediate window. What could be cooler than this 😀

Also for those that love Intellisense (well I don’t know who doesn’t !) Immediate Window also offers this feature for us developers 🙂

ImmediateWindow

Another way how to achieve this functionality is by pressing F10 instead of F5 in Visual Studio. Basically when you press F10 VS will run the Application but start debugging immediately. In this way you can use the immediate window to try out the code that you wish to execute there and then 🙂

So there you have it….

This trick that I just showed, makes my life much easier and I hope that it will help you as well 😀

Have loads of coding fun….

“C# my Name, CLR my Passion” << Marlon Grech the C# Disciple

kick it on DotNetKicks.com

One thought on “How to test C# code without running an application

  1. Pingback: Dew Drop - May 24, 2008 | Alvin Ashcraft's Morning Dew

Leave a comment