C# – Getting Started with Unit Testing in C# with Visual Studio

By | October 9, 2023

I know Visual Studio offers some Unit Testing goodies. How do I use them, how do you use them? What should I know about unit testing (assume I know nothing).

This question is similar but it does not address what Visual Studio can do, please do not mark this as a duplicate because of that. Posted as Community Wiki because I’m not trying to be a rep whore.

Best Solution

Easily the most significant difference is that the MSTest support is built in to Visual Studio and provides unit testing, code coverage and mocking support directly. In order to do the same types of things in the external (third-party) unit test frameworks generally requires multiple frameworks (a unit testing framework and a mocking framework) and other tools to do code coverage analysis.

The easist way to use the MSTest unit testing tools is to open the file you want to create unit tests for, right click in the editor window and choose the “Create Unit Tests…” menu from the context menu. I prefer putting my unit tests in a separate project, but that’s just personal perference. Doing this will create a sort of “template” test class, which will contain test methods to allow you to test each of the functions and properties of your class. At that point, you need to determine what it means for the test to pass or fail (in other words, determine what should happen given a certain set of inputs).

Generally, you end up writing tests that look similar to this:

string stringVal = "This";
Assert.IsTrue(stringVal.Length == 4);

This says that for the varaible named stringVal, the Length property should be equal to 4 after the assignment.

The resources listed in the other thread should provide a good starting point to understandng what unit testing is in general.