Microsoft Visual Studio has built-in unit-testing features, which allow you to write procedures to call various parts of your .NET code and check that the results are what you expect. Typically, the testing procedures make use of the Assert object; if an assertion fails, then the test fails; otherwise, the test succeeds as long as no errors or exceptions are encountered.
This technique has advantages over ad-hoc asserts or other testing/debugging techniques added to the main code itself. For example, when testing-oriented code is separated from the main project, you don't have to worry about removing it, adding it later if needed, or having it clutter the code. Also, well-defined unit tests are more structured and conducive to collaboration, compared to ad-hoc testing.
However, if you're new to writing unit tests in Visual Studio, you may need to overcome a few barriers to use this feature effectively. Here are a few tips to help you get started:
1. To run a test, don't use the Debug menu or F5. Instead, go to the Test menu and select the appropriate option under Run (e.g., Test | Run | All Tests).
2. Remember to make your objects accessible to your testing code with the "using" command. Similarly, if you're working with MVC architecture, reference your Models and Controllers objects as needed.
3. You may need to copy some settings from the Web.config file of your application to the App.config file of your testing project; in particular, connection strings, such as those used for Entity Framework, may not be accessible when the code is run through the unit tests. A simple workaround is to copy and paste the relevant entries within the connectionStrings section of Web.config to the corresponding section within App.config.
4. When you set up the testing project through Visual Studio, it may automatically add some unit tests. You can use these as samples to help understand how to create basic unit tests.
At New Horizons, we’re talking training everyday—and not just with a variety of clients, but with leading vendors—about industry trends and real-life challenges. And because of our close partnership with CompTIA, New Horizons is positioned to help businesses like yours leverage our knowledge experts to discuss strategies, implementation and troubleshooting.
If you would like to learn about Visual Studio, click here for information about upcoming class offerings. Also, if you found this article interesting, helpful or useful, please use the ‘Social Share’ buttons below and spread the word across your networks.