Unit test basics

Cheque 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 y'all tin can exam as private units. Visual Studio Examination Explorer provides a flexible and efficient fashion to run your unit tests and view their results in Visual Studio. Visual Studio installs the Microsoft unit of measurement testing frameworks for managed and native code. Use a unit of measurement testing framework to create unit tests, run them, and report the results of these tests. Rerun unit of measurement tests when you lot brand changes to test that your code is still working correctly. Visual Studio Enterprise tin can do this automatically with Live Unit Testing, which detects tests affected past your code changes and runs them in the background equally you type.

Unit testing has the greatest effect on the quality of your code when information technology'southward an integral function 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, purlieus, and incorrect cases of input data, and that check any explicit or implicit assumptions fabricated by the code. With test driven development, y'all create the unit tests before you write the code, so yous apply the unit tests as both pattern documentation and functional specifications.

Test Explorer can also run tertiary-party and open up source unit of measurement test frameworks that have implemented Test Explorer add-on interfaces. You tin can add many of these frameworks through the Visual Studio Extension Manager and the Visual Studio gallery. For more information, encounter Install third-party unit test frameworks.

You can speedily generate test projects and test methods from your lawmaking, or manually create the tests every bit you demand them. When you use IntelliTest to explore .Internet code, you lot can generate test information and a suite of unit tests. For every statement in the code, a test input is generated that will execute that statement. Discover out how to generate unit of measurement tests for .NET code.

Get started

For an introduction to unit testing that takes yous direct into coding, come across one of these topics:

  • Walkthrough: Create and run unit tests for .NET lawmaking

  • Walkthrough: Test driven development with Test Explorer

  • Write unit of measurement tests for C/C++ in Visual Studio

The MyBank solution example

In this article, we utilize the development of a fictional awarding chosen MyBank as an example. You don't demand the actual lawmaking 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.

MyBank Solution

MyBank Solution 2019

MyBank Solution 2022

Our offset 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 amass and manage the individual accounts.

We create a MyBank solution that contains two projects:

  • Accounts

  • BankDb

Our first attempt at designing the Accounts projection contains a class to hold basic information about an business relationship, an interface that specifies the mutual functionality of any type of account, like depositing and withdrawing avails from the account, and a form derived from the interface that represents a checking account. We begin the Accounts projects by creating the post-obit source files:

  • AccountInfo.cs defines the basic information for an account.

  • IAccount.cs defines a standard IAccount interface for an business relationship, including methods to deposit and withdraw avails from an account and to recollect the business relationship balance.

  • CheckingAccount.cs contains the CheckingAccount form that implements the IAccount interface for a checking business relationship.

Nosotros know from feel that one affair a withdrawal from a checking account must do is to make sure that the amount withdrawn is less than the business relationship remainder. Then we override the IAccount.Withdraw method in CheckingAccount with a method that checks for this status. The method might look like this:

              public void Withdraw(double amount) {     if(m_balance >= amount)     {         m_balance -= amount;     }     else     {         throw new ArgumentException(nameof(corporeality), "Withdrawal exceeds balance!");     } }                          

Now that nosotros have some code, information technology's time for testing.

Create unit of measurement examination projects and test methods (C#)

For C#, information technology is ofttimes quicker to generate the unit examination projection and unit examination stubs from your code. Or you can choose to create the unit test project and tests manually depending on your requirements. If you lot want to create unit of measurement tests from lawmaking with a third party framework you will need one of these extensions installed: NUnit or xUnit. If you lot are not using C#, skip this department and go to Create the unit test project and unit tests manually.

Generate unit exam project and unit test stubs

  1. From the code editor window, right-click and choose Create Unit of measurement Tests from the right-click carte.

    From the editor window, view the context menu

    Annotation

    The Create Unit Tests menu control is simply available for managed code that targets the .NET Framework (but non .Cyberspace Cadre).

    From the editor window, view the context menu

    Annotation

    The Create Unit Tests carte command is only available for C# code. To use this method with .Net Core or .Internet Standard, Visual Studio 2019 or later is required.

    From the editor window, view the context menu

    Note

    The Create Unit Tests carte control is only available for C# lawmaking. To apply this method with .Cyberspace Core or .NET Standard, Visual Studio 2019 or afterward is required.

  2. Click OK to take the defaults to create your unit tests, or change the values used to create and name the unit exam project and the unit of measurement tests. You can select the lawmaking that is added past default to the unit of measurement test methods.

    Create Unit Tests dialog box in Visual Studio

    Create Unit Tests dialog box in Visual Studio

  3. The unit examination stubs are created in a new unit exam project for all the methods in the class.

    The unit tests are created

    The unit tests are created

    The unit tests are created

  4. Now leap ahead to larn how to Write your tests to make your unit test meaningful, and any actress unit of measurement tests that y'all might desire to add to thoroughly test your code.

Create the unit examination project and unit tests manually

A unit test project normally mirrors the structure of a single code projection. In the MyBank case, you add together two unit examination projects named AccountsTests and BankDbTests to the MyBanks solution. The test project names are arbitrary, but adopting a standard naming convention is a good thought.

To add a unit test projection to a solution:

  1. In Solution Explorer, right-click on the solution and choose Add together > New Project.
  1. In the New Project dialog box, expand the Installed node, choose the language that you want to use for your test project, then choose Test.

  2. To use one of the Microsoft unit test frameworks, choose Unit Examination Project from the listing of projection templates. Otherwise, cull the project template of the unit test framework that y'all want to employ. To exam the Accounts project of our instance, you would proper noun the projection AccountsTests.

    Annotation

    Non all third-political party and open up source unit test frameworks provide a Visual Studio project template. Consult the framework document for data nearly creating a project.

  1. Type test in the project template search box to find a unit test project template for the examination framework that y'all desire to use. (In the examples in this topic, we use MSTest.)

  2. On the next page, name the project. To test the Accounts project of our case, y'all could name the project AccountsTests.

  1. In your unit test project, add a reference to the lawmaking projection under examination, in our case to the Accounts projection.

    To create the reference to the code project:

    1. In the unit of measurement exam projection in Solution Explorer, right-click the References or Dependencies node, then choose Add together Projection Reference or Add Reference, whichever is available.

    2. On the Reference Manager dialog box, open the Solution node and choose Projects. Select the code project name and shut the dialog box.

Each unit of measurement test project contains classes that mirror the names of the classes in the lawmaking projection. In our case, the AccountsTests project would contain the following classes:

  • AccountInfoTests class contains the unit test methods for the AccountInfo form in the Accounts project

  • CheckingAccountTests grade contains the unit test methods for CheckingAccount class.

Write your tests

The unit test framework that you apply and Visual Studio IntelliSense will guide you through writing the code for your unit tests for a code projection. To run in Exam Explorer, well-nigh frameworks require that you add specific attributes to identify unit test methods. The frameworks too provide a style—usually through assert statements or method attributes—to signal whether the test method has passed or failed. Other attributes identify optional setup methods that are at course initialization and before each examination method and teardown methods that are run after each test method and before the form is destroyed.

The AAA (Adapt, Deed, Assert) pattern is a common manner of writing unit tests for a method under test.

  • The Arrange department of a unit test method initializes objects and sets the value of the information that is passed to the method under test.

  • The Human activity section invokes the method under test with the arranged parameters.

  • The Affirm section verifies that the action of the method under test behaves as expected. For .Net, methods in the Assert class are often used for verification.

To test the CheckingAccount.Withdraw method of our instance, nosotros tin can write two tests: 1 that verifies the standard beliefs of the method, and one that verifies that a withdrawal of more than than the balance volition neglect (The following code shows an MSTest unit exam, which is supported in .Internet.). In the CheckingAccountTests class, nosotros add the post-obit methods:

              [TestMethod] public void Withdraw_ValidAmount_ChangesBalance() {     // arrange     double currentBalance = x.0;     double withdrawal = 1.0;     double expected = 9.0;     var business relationship = new CheckingAccount("JohnDoe", currentBalance);      // act     account.Withdraw(withdrawal);      // assert     Assert.AreEqual(expected, account.Rest); }  [TestMethod] public void Withdraw_AmountMoreThanBalance_Throws() {     // accommodate     var account = new CheckingAccount("John Doe", 10.0);      // human activity and assert     Assert.ThrowsException<System.ArgumentException>(() => business relationship.Withdraw(20.0)); }                          

For more than information well-nigh the Microsoft unit of measurement testing frameworks, see ane of the post-obit topics:

  • Unit test your lawmaking

  • Writing unit tests for C/C++

  • Use the MSTest framework in unit tests

Set timeouts for unit tests

If you lot're using the MSTest framework, you tin apply the TimeoutAttribute to set up a timeout on an private test method:

              [TestMethod] [Timeout(2000)]  // Milliseconds public void My_Test() { ... }                          

To set the timeout to the maximum allowed:

              [TestMethod] [Timeout(TestTimeout.Infinite)]  // Milliseconds public void My_Test () { ... }                          

Run tests in Test Explorer

When yous build the examination project, the tests appear in Exam Explorer. If Examination Explorer is non visible, cull Test on the Visual Studio menu, cull Windows, and and so choose Test Explorer (or press Ctrl + E, T).

Unit Test Explorer

Unit Test Explorer

Unit Test Explorer

As y'all run, write, and rerun your tests, the Test Explorer tin display the results in groups of Failed Tests, Passed Tests, Skipped Tests and Not Run Tests. You can choose unlike group by options in the toolbar.

You tin 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 tin run any selection of the tests at whatsoever 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 exam.

Run and view tests

The Exam Explorer toolbar helps you lot observe, organize, and run the tests that you lot are interested in.

Run tests from the Test Explorer toolbar

Run tests from the Test Explorer toolbar

Run tests from the Test Explorer toolbar

You can choose Run All to run all your tests (or press Ctrl + R, V), or cull Run to choose a subset of tests to run (Ctrl + R, T). Select a test to view the details of that test in the examination details pane. Cull Open Test from the correct-click bill of fare (Keyboard: F12) to display the source code for the selected test.

If individual tests have no dependencies that forbid them from existence run in any order, plough on parallel examination execution with the Screenshot of the Parallel test execution toggle button on the Visual Studio Test Explorer toolbar. toggle push on the toolbar. This tin noticeably reduce the time taken to run all the tests.

If individual tests take no dependencies that prevent them from existence run in any gild, plough on parallel test execution in the settings bill of fare of the toolbar. This tin can noticeably reduce the time taken to run all the tests.

Run tests after every build

Button Description
Run after build To run your unit of measurement tests afterwards each local build, cull Test on the standard menu, and and so cull Run Tests After Build on the Exam Explorer toolbar.

Annotation

Running unit of measurement tests after each build requires Visual Studio 2017 Enterprise edition or Visual Studio 2019. In Visual Studio 2019, the feature is bachelor 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 Afterwards Build.

Filter and grouping the examination list

When you lot accept a large number of tests, you can type in the Examination Explorer search box to filter the list past the specified cord. You lot can restrict your filter outcome more than by choosing from the filter list.

Search filter categories

Search filter categories

Search filter categories

Button Description
Test Explorer group button To grouping your tests past category, cull the Group By button.

For more information, see Run unit tests with Test Explorer.

Q&A

Q: How do I debug unit of measurement tests?

A: Employ Examination Explorer to start a debugging session for your tests. Stepping through your lawmaking with the Visual Studio debugger seamlessly takes you back and along between the unit tests and the project under test. To start debugging:

  1. In the Visual Studio editor, ready a breakpoint in one or more test methods that you want to debug.

    Annotation

    Because test methods tin can run in whatever club, set up breakpoints in all the test methods that you want to debug.

  2. In Test Explorer, select the test methods and then choose Debug Selected Tests from the shortcut menu.

Learn more than details about debugging unit of measurement tests.

Q: If I'm using TDD, how do I generate code from my tests?

A: Apply Quick Deportment to generate classes and methods in your project code. Write a statement in a test method that calls the grade or method that you want to generate, and so open the lightbulb that appears under the mistake. If the call is to a constructor of the new class, choose Generate type from the carte and follow the wizard to insert the class in your code project. If the telephone call is to a method, cull Generate method from the IntelliSense menu.

Generate Method Stub Quick Action Menu

Generate Method Stub Quick Action Menu

Generate Method Stub Quick Action Menu

Q: Can I create unit of measurement tests that take multiple sets of information as input to run the test?

A: Aye. Data-driven test methods let you test a range of values with a single unit test method. Utilize a DataSource aspect for the test method that specifies the data source and table that contains the variable values that y'all want to test. In the method trunk, you assign the row values to variables using the TestContext.DataRow[ ColumnName ] indexer.

Annotation

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 ii integers.

To create a data-driven test for the AddIntegerHelper method, nosotros kickoff 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 upshot. Nosotros fill a number of rows with appropriate values.

              [DataSource(     @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Projects\MyBank\TestData\AccountsTest.accdb",     "AddIntegerHelperData" )] [TestMethod()] public void AddIntegerHelper_DataDrivenValues_AllShouldPass() {     var target = new CheckingAccount();     int x = Catechumen.ToInt32(TestContext.DataRow["FirstNumber"]);     int y = Catechumen.ToInt32(TestContext.DataRow["SecondNumber"]);     int expected = Catechumen.ToInt32(TestContext.DataRow["Sum"]);     int actual = target.AddIntegerHelper(x, y);     Assert.AreEqual(expected, bodily); }                          

The attributed method runs once for each row in the table. Examination Explorer reports a exam failure for the method if whatsoever of the iterations fail. The test results particular pane for the method shows you the pass/fail status method for each row of data.

Learn more about data-driven unit tests.

Q: Tin I view how much of my code is tested past my unit tests?

A: Yeah. You can determine the amount of your code that is really existence tested by your unit of measurement tests by using the Visual Studio code coverage tool in Visual Studio Enterprise. Native and managed languages and all unit examination frameworks that tin can be run by the Unit Examination Framework are supported.

You tin can run code coverage on selected tests or on all tests in a solution. The Code Coverage Results window displays the per centum of the blocks of production code that were exercised by line, function, class, namespace and module.

To run code coverage for exam methods in a solution, cull Test > Analyze Code Coverage for All Tests.

Coverage results appear in the Code Coverage Results window.

Code coverage results

Code coverage results

Learn more about code coverage.

Q: Tin can I test methods in my code that have external dependencies?

A: Aye. If yous have Visual Studio Enterprise, Microsoft Fakes tin can exist used with test methods that you write by using unit of measurement test frameworks for managed lawmaking.

Microsoft Fakes uses two approaches to create substitute classes for external dependencies:

  1. 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 grade.

  2. Shims use runtime instrumentation to divert calls to a target method to a substitute shim method for non-virtual methods.

In both approaches, y'all utilise the generated delegates of calls to the dependency method to specify the behavior that you want in the test method.

Acquire more about isolating unit test methods with Microsoft Fakes.

Q: Tin I apply other unit examination 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 so select your installed frameworks here:

Select other installed unit test framework

Your unit test stubs will exist created using the selected framework.