The two new things you will notice in this snippet of code is the TestClass and TestMethod tags, which certainly don’t just float around in normal code. These tags are what allow Visual Studio’s built in testing framework to recognize this particular class as a class that contains unit tests, and to treat the method TryShootBug as a test case, instead of just an ordinary method. Visual Studio Deep Dive: Unit Tests. This is the repository for the LinkedIn Learning course Visual Studio Deep Dive: Unit Tests. The full course is available from LinkedIn Learning. If you are a responsible programmer, you regularly test your code to make sure it behaves the way you expect it to behave. Unit Test Project (.NET Framework) There is a project type in Visual Studio that is dedicated to creating tests. This is appropriately named the Unit Test Project. We would want to use this type of project to create tests that verify the classes we build work as intended. The unit test project type creates a new assembly with the test code we. It helps in writing effective unit tests using MSTest framework to test software applications. MSTest is a number-one open-source test framework that is shipped along with the Visual Studio IDE. It is also referred to as the Unit Testing Framework. However, MSTest is the same within the developer community. MSTest is used to run tests. Trace.Write - The Visual Studio test harness will capture this and show it in the test output. Does appear in the Visual Studio Output (or Immediate) Window when debugging a unit test (but not when simply running the test without debugging). By default available in both Debug and Release builds (that is, when TRACE constant is defined).
-->Check that your code is working as expected by creating and running unit tests. It's called unit testing because you break down the functionality of your program into discrete testable behaviors that you can test as individual units. Visual Studio Test Explorer provides a flexible and efficient way to run your unit tests and view their results in Visual Studio. Visual Studio installs the Microsoft unit testing frameworks for managed and native code. Use a unit testing framework to create unit tests, run them, and report the results of these tests. Rerun unit tests when you make changes to test that your code is still working correctly. Visual Studio Enterprise can do this automatically with Live Unit Testing, which detects tests affected by your code changes and runs them in the background as you type.
Unit testing has the greatest effect on the quality of your code when it's an integral part of your software development workflow. As soon as you write a function or other block of application code, create unit tests that verify the behavior of the code in response to standard, boundary, and incorrect cases of input data, and that check any explicit or implicit assumptions made by the code. With test driven development, you create the unit tests before you write the code, so you use the unit tests as both design documentation and functional specifications.
Test Explorer can also run third-party and open source unit test frameworks that have implemented Test Explorer add-on interfaces. You can add many of these frameworks through the Visual Studio Extension Manager and the Visual Studio gallery. For more information, see Install third-party unit test frameworks.
You can quickly generate test projects and test methods from your code, or manually create the tests as you need them. When you use IntelliTest to explore .NET code, you can generate test data and a suite of unit tests. For every statement in the code, a test input is generated that will execute that statement. Find out how to generate unit tests for .NET code.
Get started
For an introduction to unit testing that takes you directly into coding, see one of these topics:
The MyBank solution example
In this article, we use the development of a fictional application called MyBank
as an example. You don't need the actual code to follow the explanations in this topic. Test methods are written in C# and presented by using the Microsoft Unit Testing Framework for Managed Code. However, the concepts are easily transferred to other languages and frameworks.
Our first attempt at a design for the MyBank
application includes an accounts component that represents an individual account and its transactions with the bank, and a database component that represents the functionality to aggregate and manage the individual accounts.
We create a MyBank
solution that contains two projects:
Accounts
BankDb
Our first attempt at designing the Accounts
project contains a class to hold basic information about an account, an interface that specifies the common functionality of any type of account, like depositing and withdrawing assets from the account, and a class derived from the interface that represents a checking account. We begin the Accounts projects by creating the following source files:
AccountInfo.cs defines the basic information for an account.
IAccount.cs defines a standard
IAccount
interface for an account, including methods to deposit and withdraw assets from an account and to retrieve the account balance.CheckingAccount.cs contains the
CheckingAccount
class that implements theIAccount
interface for a checking account.
We know from experience that one thing a withdrawal from a checking account must do is to make sure that the amount withdrawn is less than the account balance. So we override the IAccount.Withdraw
method in CheckingAccount
with a method that checks for this condition. The method might look like this:
Now that we have some code, it's time for testing.
Create unit test projects and test methods
For C#, it is often quicker to generate the unit test project and unit test stubs from your code. Or you can choose to create the unit test project and tests manually depending on your requirements. If you want to create unit tests from code with a 3rd party framework you will need one of these extensions installed: NUnit or xUnit. If you are not using C#, skip this section and go to Create the unit test project and unit tests manually.
Generate unit test project and unit test stubs
From the code editor window, right-click and choose Create Unit Tests from the right-click menu.
Note
The Create Unit Tests menu command is only available for managed code that targets the .NET Framework (but not .NET Core).
Note
The Create Unit Tests menu command is only available for C# code.
Click OK to accept the defaults to create your unit tests, or change the values used to create and name the unit test project and the unit tests. You can select the code that is added by default to the unit test methods.
The unit test stubs are created in a new unit test project for all the methods in the class.
Now jump ahead to learn how to add code to the unit test methods to make your unit test meaningful, and any extra unit tests that you might want to add to thoroughly test your code.
Create the unit test project and unit tests manually
A unit test project usually mirrors the structure of a single code project. In the MyBank example, you add two unit test projects named AccountsTests
and BankDbTests
to the MyBanks
solution. The test project names are arbitrary, but adopting a standard naming convention is a good idea.
To add a unit test project to a solution:
- In Solution Explorer, right-click on the solution and choose Add > NewProject.
In the New Project dialog box, expand the Installed node, choose the language that you want to use for your test project, and then choose Test.
To use one of the Microsoft unit test frameworks, choose Unit Test Project from the list of project templates. Otherwise, choose the project template of the unit test framework that you want to use. To test the
Accounts
project of our example, you would name the projectAccountsTests
.Note
Not all third-party and open source unit test frameworks provide a Visual Studio project template. Consult the framework document for information about creating a project.
Use the project template search box to find a unit test project template for the test framework that you want to use.
On the next page, name the project. To test the
Accounts
project of our example, you could name the projectAccountsTests
.
In your unit test project, add a reference to the code project under test, in our example to the Accounts project.
To create the reference to the code project:
Select the project in Solution Explorer.
On the Project menu, choose Add Reference.
On the Reference Manager dialog box, open the Solution node and choose Projects. Select the code project name and close the dialog box.
Each unit test project contains classes that mirror the names of the classes in the code project. In our example, the AccountsTests
project would contain the following classes:
AccountInfoTests
class contains the unit test methods for theAccountInfo
class in theAccounts
projectCheckingAccountTests
class contains the unit test methods forCheckingAccount
class.
Write your tests
The unit test framework that you use and Visual Studio IntelliSense will guide you through writing the code for your unit tests for a code project. To run in Test Explorer, most frameworks require that you add specific attributes to identify unit test methods. The frameworks also provide a way—usually through assert statements or method attributes—to indicate whether the test method has passed or failed. Other attributes identify optional setup methods that are at class initialization and before each test method and teardown methods that are run after each test method and before the class is destroyed.
The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test.
The Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test.
The Act section invokes the method under test with the arranged parameters.
The Assert section verifies that the action of the method under test behaves as expected.
To test the CheckingAccount.Withdraw
method of our example, we can write two tests: one that verifies the standard behavior of the method, and one that verifies that a withdrawal of more than the balance will fail. In the CheckingAccountTests
class, we add the following methods:
For more information about the Microsoft unit testing frameworks, see one of the following topics:
Set timeouts for unit tests
If you're using the MSTest framework, you can use the TimeoutAttribute to set a timeout on an individual test method:
To set the timeout to the maximum allowed:
Run tests in Test Explorer
When you build the test project, the tests appear in Test Explorer. If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T).
As you run, write, and rerun your tests, the Test Explorer can display the results in groups of Failed Tests, Passed Tests, Skipped Tests and Not Run Tests. You can choose different group by options in the toolbar.
You can also filter the tests in any view by matching text in the search box at the global level or by selecting one of the pre-defined filters. You can run any selection of the tests at any time. The results of a test run are immediately apparent in the pass/fail bar at the top of the explorer window. Details of a test method result are displayed when you select the test.
Run and view tests
The Test Explorer toolbar helps you discover, organize, and run the tests that you are interested in.
You can choose Run All to run all your tests (or press Ctrl + R, V), or choose Run to choose a subset of tests to run (Ctrl + R, T). Select a test to view the details of that test in the test details pane. Choose Open Test from the right-click menu (Keyboard: F12) to display the source code for the selected test.
If individual tests have no dependencies that prevent them from being run in any order, turn on parallel test execution with the toggle button on the toolbar. This can noticeably reduce the time taken to run all the tests.
If individual tests have no dependencies that prevent them from being run in any order, turn on parallel test execution in the settings menu of the toolbar. This can noticeably reduce the time taken to run all the tests.
Run tests after every build
Button | Description |
---|---|
To run your unit tests after each local build, choose Test on the standard menu, and then choose Run Tests After Build on the Test Explorer toolbar. |
Note
Running unit tests after each build requires Visual Studio 2017 Enterprise edition or Visual Studio 2019. In Visual Studio 2019, the feature is available in Community and Professional edition, in addition to Enterprise edition.
To run your unit tests after each local build, open the settings icon in the Test Explorer toolbar and select Run Tests After Build.
Filter and group the test list
When you have a large number of tests, you can type in the Test Explorer search box to filter the list by the specified string. You can restrict your filter event more by choosing from the filter list.
Button | Description |
---|---|
To group your tests by category, choose the Group By button. |
For more information, see Run unit tests with Test Explorer.
Q&A
Q: How do I debug unit tests?
A: Use Test Explorer to start a debugging session for your tests. Stepping through your code with the Visual Studio debugger seamlessly takes you back and forth between the unit tests and the project under test. To start debugging:
In the Visual Studio editor, set a breakpoint in one or more test methods that you want to debug.
Note
Because test methods can run in any order, set breakpoints in all the test methods that you want to debug.
In Test Explorer, select the test methods and then choose Debug Selected Tests from the shortcut menu.
Learn more details about debugging unit tests.
Q: If I'm using TDD, how do I generate code from my tests?
A: Use Quick Actions to generate classes and methods in your project code. Write a statement in a test method that calls the class or method that you want to generate, then open the lightbulb that appears under the error. If the call is to a constructor of the new class, choose Generate type from the menu and follow the wizard to insert the class in your code project. If the call is to a method, choose Generate method from the IntelliSense menu.
Q: Can I create unit tests that take multiple sets of data as input to run the test?
A: Yes. Data-driven test methods let you test a range of values with a single unit test method. Use a DataSource
attribute for the test method that specifies the data source and table that contains the variable values that you want to test. In the method body, you assign the row values to variables using the TestContext.DataRow[
ColumnName]
indexer.
Note
These procedures apply only to test methods that you write by using the Microsoft unit test framework for managed code. If you're using a different framework, consult the framework documentation for equivalent functionality.
For example, assume we add an unnecessary method to the CheckingAccount
class that is named AddIntegerHelper
. AddIntegerHelper
adds two integers.
To create a data-driven test for the AddIntegerHelper
method, we first create an Access database named AccountsTest.accdb and a table named AddIntegerHelperData
. The AddIntegerHelperData
table defines columns to specify the first and second operands of the addition and a column to specify the expected result. We fill a number of rows with appropriate values.
The attributed method runs once for each row in the table. Test Explorer reports a test failure for the method if any of the iterations fail. The test results detail pane for the method shows you the pass/fail status method for each row of data.
Learn more about data-driven unit tests.
Q: Can I view how much of my code is tested by my unit tests?
A: Yes. You can determine the amount of your code that is actually being tested by your unit tests by using the Visual Studio code coverage tool in Visual Studio Enterprise. Native and managed languages and all unit test frameworks that can be run by the Unit Test Framework are supported.
You can run code coverage on selected tests or on all tests in a solution. The Code Coverage Results window displays the percentage of the blocks of product code that were exercised by line, function, class, namespace and module.
To run code coverage for test methods in a solution, choose Test > Analyze Code Coverage for All Tests.
Coverage results appear in the Code Coverage Results window.
Learn more about code coverage .
Q: Can I test methods in my code that have external dependencies?
A: Yes. If you have Visual Studio Enterprise, Microsoft Fakes can be used with test methods that you write by using unit test frameworks for managed code.
Microsoft Fakes uses two approaches to create substitute classes for external dependencies:
Stubs generate substitute classes derived from the parent interface of the target dependency class. Stub methods can be substituted for public virtual methods of the target class.
Shims use runtime instrumentation to divert calls to a target method to a substitute shim method for non-virtual methods.
In both approaches, you use the generated delegates of calls to the dependency method to specify the behavior that you want in the test method.
Learn more about isolating unit test methods with Microsoft Fakes.
Q: Can I use other unit test frameworks to create unit tests?
A: Yes, follow these steps to find and install other frameworks. After you restart Visual Studio, reopen your solution to create your unit tests, and then select your installed frameworks here:
Your unit test stubs will be created using the selected framework.
This topic describes a step-by-step process of creating the simplest unit test in Microsoft Visual Studio 2010 (C++) for a CLR Console Application. Using this example, you can learn to create your own Unit-tests. The example also demonstrates the use of the Assert class for testing the work functions.
Contents
- Instructions
- 4. Creating a test
- 4.5. Connection of the “MaxApp.cpp” module of the MaxApp project to the TestMaxApp project
- 4. Creating a test
Search other websites:
The task
For a CLR Console Application, develop a Unit-test that tests the Max3() function, which defines the maximum element of three numbers. For the Max3() function, set the TestMax() test method. Check the function.
Instructions
1. Create a CLR Console Application
After starting Microsoft Visual Studio, you must select
As a result, the New Project window opens (Figure 1), in which you need to select template
Project name set as MaxApp (or, if desired, another). In our case, the project folder is set to “E:Test” (the “Location:” field).
Figure 1. Creating an application using the CLR Console Application template
After selecting OK, an application of the CLR Console Application type will be created.
After creating the application, the Microsoft Visual Studio text box will have an approximate view, as shown in Figure 2.
Figure 2. Application view after creating
As you can see in Figure 2, the MyApp.cpp module contains the connection of the module “stdafx.h” and the main() function, which is the entry point to the program (this function is associated with the C++ program).
2. Implementation of function Max()
Before the declaration of the main() function, the text of the Max() function is entered, which looks like this:
This function will need to be tested using Unit-test in Microsoft Visual Studio.
3. The text of the program, which must be tested
At the moment, the text of the program you want to test is as follows:
Because this program will be tested from another testing module, then nothing needs to be entered in the main() function. Since, according to the condition of the task, you need to test the operation of the Max() function. But this will already be done from the testing module. At the moment our program is ready for testing.
4. Creating a test
The test is created by a separate project in the Solution. The program, which will be tested does not know about it. The test program that will test calls the functions of the program under test. In our case, the test program will call the function
4.1. Adding a new project to the solution
To create a test, you need to create a new project in the Solution. To do this, a sequence of commands is called in Visual Studio
This will open the “Add New Project” window, shown in Figure 3.
Figure 3. The “Add New Project” window
In the window a templates group of Visual C ++ – Test is selected. From the proposed templates, the project template “Test Project” is selected. The “Name” field indicates the name of the project that will test our program. You need to set, for example, TestMaxApp. The project is located in a separate folder “E:TestMaxApp”. After selecting OK, the system creates new project files that will be tested, as shown in Figure 4. A file (module) is created with the name “UnitTest1.cpp”. In this file, you need to enter the code that will test the Max() function from the MaxApp.cpp module.
Figure 4. The text of UnitTest1.cpp file. The Solution Explorer window with the displayed projects TestMaxApp and MaxApp
4.2. The structure of solution
As you can see in Figure 4, Solution Explorer displays the Solution Items structure, which contains two projects:
- the MaxApp project. This is a project created using the CLR Console Application template with the Max() function, which to be tested;
- the TestMaxApp project. This project is designed to test the functions of the MaxApp project. The program code that will test the Max() function will be added to the project file UnitTest1 of the TestMaxApp project.
Both projects can be executed independently of each other.
4.3. The text of the test file “UnitTest1.cpp”. Attributes [TestMethod] and [TestClass]
In the TestMaxApp project, the UnitTest1.cpp test file is the main test file. This file contains methods that will test the functions of the project “MaxApp.cpp”. The TestMaxApp project can contain any number of files that contain tests (for example, UnitTest2.cpp, UnitTest3.cpp, etc.).
Listing of the UnitTest1.cpp file generated by MS Visual Studio is as follows:
As you can see from the above code, the file contains a class named UnitTest1. The class has a public method named TestMethod1().Before implementation of TestMethod1() method, the [TestMethod] attribute is placed. This means that in the body of the method, you need to enter code that will test the functions of the MaxApp project.
In the class, you can enter any number of methods that will test different functions from different modules. The main thing is that these methods are marked with the attribute [TestMethod]. For example, if you want to add a second test method named MySecondTestMethod(), you need to enter approximately the following code into the class body:
Similarly, the [TestClass] attribute is placed before the UnitTest1 class. This means that there are testing methods in the class.
4.4. Making changes in the text of UnitTest1
You can change the method names and add new methods that are marked with the [TestMethod] attribute in the UnitTest1.cpp module. With this in mind, in the UnitTest1.cpp text, the TestMethod1() method must be renamed to TestMax().
After the changes have been made, the abbreviated text of UnitTest1.cpp file module will look like:
4.5. Connection of the “MaxApp.cpp” module of the MaxApp project to the TestMaxApp project
To access the Max() function of the “MaxApp.cpp” module of the MaxApp project from the TestMaxApp project, you need to call this module using the #include directive.
There are 2 methods of this connection:
- connect the file “MaxApp.cpp”, specifying its full name on the disk (or on another source);
- in the references to the Microsoft Visual Studio assemblies, configure the folder with the MaxApp project so that it is automatically connected.
After this, you can access the “MaxApp.cpp” file by its abbreviated name. In this topic, both methods are described.
4.5.1. Method 1. Connection with a full name request
This method is more simplified. It is convenient when you need to connect a small number of files to the project for testing.
In the TestMaxApp project, in the “UnitTest1.cpp” file, after connecting namespaces, you need to set the following line:
This specifies the full name of the MaxApp.cpp file on the disk, in which the Max() function is located, which you need to test.
4.5.2. Method 2. Connection with an abbreviated name
This method is effective when you need to test several modules of different projects. A whole directory (folder) is connected with the files of the tested project. In our case, it is needed to use the folder:
in the list of references to assemblies (projects) that automatically connect to the TestMaxApp project. After that, you can connect the MaxApp.cpp module by abbreviated name
avoiding the use of a long name as shown in section 4.5.1.
First of all, the “References …” command is called from the TestMaxApp context menu as shown in Figure 5. Another way to call – the command Project-> References … (previously need to be select TestMaxApp project).
Figure 5. Calling the default references viewer window for assemblies that are used in the TestMaxApp project
This opens the “TestMaxApp Property Pages” window which is shown in Figure 6.
Figure 6. The “TestMaxApp Property Pages” window, command “Add New Reference …”
In the “TestMaxApp Property Pages” window, you first need to activate the “Common Properties” -> “Framework and References” tab.
Then you need to select the command “Add New Reference …”. This command allows adding new folders with modules to the project, methods (functions, resources) of which can then be included in the project by the #include directive. After selecting the command, the Add Reference window, shown in Figure 7, opens.
Figure 7. The “Add Reference” window with the displayed projects in the current solution
In the “Add Reference” window, the Project tab displays the project folders that are used in this solution. In our case, only one MaxApp project is displayed, which is located in the folder
After selecting OK, you return to the previous window, in which the reference to the MaxApp project will be displayed in the list of references to the assemblies.
Figure 8. The “TestMaxApp Property Pages” window after adding the MaxApp project to the list of public assemblies
That’s not all! The next step is to connect the MaxTest project folder to the “Include Directories” list.
To do this, you must first activate the line
as shown in Figure 9.
Figure 9. The “TestMaxApp Property Pages” window, line “Include Directories”
In the “General” list, “Include Directories” is selected. As a result, a dropdown list is opened, in which you need to select the command “<Edit …>”. After that, the “Include Directories” window shown in Figure 10 opens.
Figure 10. The “New Line” command and the folder selection button with the files that connect
In the “Include Directories” window, add a new line with the “New Line” command and select the folder with the MaxApp project, as shown in Figure 10. After selecting the “…” button, the standard Windows window opens to select the desired folder. In our case, you need to select a folder
After selecting, the Include Directories window will have the appearance as shown in Figure 11.
Figure 11. The Include Directories window after selecting the folder E:TestMaxAppMaxApp
To go to the previous window, select OK.
Figure 12. The TextMaxApp Property Pages window after configuring the line “Include Directories”
To proceed to writing the program test code, select OK.
After the performed actions, all files from the folder
can be connected by abbreviated name, for example:
4.6. Writing code in the TestMax() method
The code that tests the Max() function fits into the body of the TestMax() method of the “UnitTest1.cpp” module. The code fragment of the TestMax() method looks like this:
Visual Studio Unit Test Tutorial
The above code calls the function AreEqual() from the Assert class. This function compares the value that was returned from the Max() function and the value 6. In this case, the number 7 (maximum) is compared with the number 6. For this way, the test will not be passed, since 7 is not equal to 6. As a result, the Assert::AreEqual() function throws an exception, which will be displayed in a special window (see paragraph 5).
5. Running the test and checking the test results
In Microsoft Visual Studio, a special menu of commands, called Test, is implemented to work with Unit-tests. To run the test, you must select one of the commands
or
as shown in Figure 13.
Figure 13. Calling the test command and viewing the result
After starting the test, the result can be viewed at the bottom of the “Test Results” window. As you can see, the test is failed. This is logical, because in the function Assert::AreEqual() we compare the numbers 6 and 7, which are different from each other. Here the number 6 is specially introduced instead of the number 7.
Visual Studio Unit Test C#
If instead of 6 you enter the correct answer – the number 7 (maximum between 5, 6, 7), then the test will be passed. In this case, the text of the TestMax() method will be as follows:
The result window is shown in Figure 14.
Figure 14. The test result for the case if you enter the correct checking
Now we can conclude that the function Max() was developed correctly.
6. The code of UnitTest1 module
Below is the text of UnitTest1.cpp, which tests the Max() function from the module “MaxApp.cpp”:
7. Conclusion. Interaction between projects
In this topic, two projects are developed in the solution. One MaxApp project contains the Max() function to be tested. The second project TestMaxApp contains methods that test.
In Microsoft Visual Studio, each project is run using various menu commands. For example, the MaxApp project is launched in the standard way from the Run menu. And the test project TestMaxApp is run from the special menu “Test”.