Visual Studio Unit Test
2021年11月7日Download here: http://gg.gg/whqlq
The creation of unit tests is an important step in ensuring the quality of a project. In general, most public methods are tested, but what if you want to test a non-public part of the project? Putting all classes of your.Net project in public is not recommended. You can 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. Test Explorer is a handy feature of Visual Studio that allows you to run unit tests within a project, customize how they’re run, and interpret their output. Test Explorer allows you to manipulate the order that unit tests are run, create custom playlists to segment out which unit tests run, and run tests in various user-defined groups.
*Visual Studio Unit Test Mock
*Visual Studio Unit Test
*Visual Studio Unit Test Async
*Visual Studio Unit Test Framework
*Visual Studio Unit Test Project
*Visual Studio Unit Testing
When you find yourself (or your company) with more code than anyone could ever test by hand, what can you do? Well, unit testing has always been the perfect solution, as you can run tests that check more data than a person could in a day in a matter of milliseconds. So today I’ll take a look into a few popular C# unit testing frameworks and try them out first hand so you can choose which one best suits your project.
Unit tests can be run as often as you want, on as many different kinds of data as you want and with next to no human involvement beyond once the tests are written.
Not only that, but using code to test code will often result in you noticing flaws with your program that would have been very difficult to spot from a programmer’s viewpoint.Raygun lets you detect and diagnose errors and performance issues in your codebase with ease It takes minutes to add Raygun into your software. Be alerted to issues affecting end users and replicate problems 1,000x faster than using logs and incomplete information from users. Learn more and try Raygun free for 14 days. Popular C# unit testing frameworks
The unit testing frameworks I’ll be testing are:
*NUnit
*XUnit
*Built-in Visual Studio testing tools
All of these unit testing frameworks offer a similar end goal, to help make writing unit tests faster, simpler and easier! But there are still a few key differences between them. Some are more focused towards powerful complex tests, while others rank simplicity and usability as a higher priority. First up is Microsoft’s own built in Visual Studio unit testing tools
In most versions since 2005, Visual Studio has come with a built in testing framework supported by Microsoft. This framework certainly wins the most points for installation. Though if your copy of Visual Studio doesn’t come with it already included you are going to have to jump though a few hoops to get it going. (We wrote a review of the 2017 version of Visual Studio here.)
This framework is the simplest of the three, and uses an easy to understand method attribute structure (much like most testing frameworks) where you are able to add tags such as ‘[TestClass]’and ‘[TestMethod]’to your code in order to get testing.
Visual Studio even has a UI panel dedicated to visualizing your tests, which can be found under Test -> Windows -> Test Explorer.
Now before we dive into trying out this testing framework let’s introduce our example classes that need testing.
First we have a Raygun, which we can fireand recharge. The only thing we need to keep track of with our Raygun is it’s ammo, which can run out.
We also have a bug, which we can shootat with our Raygun. But this bug has the ability to dodgeour attempts to shoot it. If we shoot at a bug after it has just dodged, we will miss. Though if we hit the bug square on, it’s safe to assume that it will be dead.
These two classes are defined as follows:
Seems simple enough, but we need to make sure that our Rayguns and bugs behave as we want them to.
So then it’s time to write some unit tests! (We wrote about how to write robust unit tests in C# here.)
First up let’s try a simple situation where we want to shootat, and hit, a bug.What we would expect is that afterwards the bug will be dead, and the Raygun will still have a bit of juice left in it.
Well, let’s see if we are right:
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.
Since these tools are built for Visual Studio, running your tests from within Visual Studio is very simple.Just right click on any[TestMethod]tags as shown:
And would you look at that, the test passed. Looks like our Raygun can at least hit a stationary bug.
Of course this is only showing the bare basics of what Visual Studio’s testing tools can do.
Some other very useful tags you will surely be using are the [TestInitialize]and [TestCleanup]tags.These tags allow you to specify code that is run before(initialize) and after(cleanup) every individual test is run.
So if you want to reload your Raygun after every encounter like a stylish gunslinger, then this should do the trick:
Stylish.
While we are still talking about the Visual Studio testing tools I’ll quickly mention the [ExpectedException]tag, which is incredibly useful for when you want to deliberately cause an exception in your test (which you will certainly want to do at some point to make sure your program isn’t accepting data it shouldn’t).
Here’s a quick example of how you would write a test that results in an exception:
Don’t worry about the index out of bounds exception, thanks to the [ExpectedException]tag the exception will be treated as a success and your test will pass. On the contrary if the exception isn’t thrown then the test will fail. Anyway, it’s about time we moved on to some more testing platforms!
Overall the built in Visual Studio testing tools do exactly what they say on the box. They are simple, easy to use and handle all the basic testing functionality you would need. Plus if you’re already working in Visual Studio then they are already ready to use!Next up is arguably the most popular C# testing platform, NUnitVisual Studio Unit Test Mock
NUnit is an incredibly widely used tool for testing, and it serves as an excellent example of the open source unit testing frameworks. It’s a broad and powerful testing solution. In fact it’s what we use here at Raygun for the bulk of our unit testing.
NUnit is installed via a NuGet package, which you can search for within Visual Studio.The packages I’ve used for this example are NUnitand NUnit.ConsoleRunner, though you also have the option of installing a GUI-based plugin for Visual Studio.
NUnit uses a very similar attribute style system just like the visual studio testing tools, but now we will be referring to a [TestClass] as a [TestFixture],and a [TestMethod] as simply a [Test].
Now let’s go back to our Rayguns and bugs and have a look at another example, but this time using NUnit.
This time let’s make sure our dodgesand ammoare working properly, so let’s try and shoot a much more mobile bug:
Notice the new [TestFixture]and [Test]tags.
Now in order to run this test using NUnit, we need to seek the command line(unless of course you’ve chosen to install a GUI based plugin.)
First, you must make sure you are in your project’s root directory (e.g. C:Users</span>yourUserNameDocumentsVisual Studio 2015Projects</span>YourProjectName) and then enter the following command in a new cmd window:
packagesNUnit.ConsoleRunner.3.6.0toolsnunit3-console.exe YourProjectNamebinDebug</span>YourProjectName.dll
Assuming everything is set up properly, the NUnit console runner will run all the tests in your project and give you a nice little report on how things went:
Looks like our bug sure can dodge and our Raygun can certainly run out of ammo!
One feature of NUnit that makes it incredibly useful is the ability to include parameters in your tests!
This means that you can write a test case with arguments, then easily run the same test with a range of unique data. This removes the need to write unique test cases for every set of arguments you want to test.
Here’s a quick example test case we could use to make sure our Raygun was actually running out of ammoat the right time, in a much smarter way than before:
Excellent, with this one test case we were able to make sure a Raygun which has fired two shots still has ammo, while one that has fired three is empty. And thanks to the [TestCase]tag we were easily able to test a whole bunch of other values while we were at it!
Overall NUnit is an excellent testing framework, and as you delve deeper into what it can offer, it surely exceeds what Microsoft’s built in testing can offer.
Anyway, let’s look at our last testing framework, and our last attempt as shooting bugs with Rayguns!If you like the sound of Facts and Theories, then it’s time to look at XUnit
XUnit is an open source testing platform with a larger focus in extensibility and flexibility. XUnit follows a more community minded development structure and focuses on being easy to expand upon.
XUnit actually refers to a grouping of frameworks, but we will be focusing on the C# version.Other versions include JUnit, a very well known testing framework for Java.XUnit also uses a more modern and unique style of testing, by doing away with the standard [test] [testfixture] terminology and using new fancy tags like Factsand Theories.
NUnit and XUnit are actually quite similar in many ways, as NUnit serves as a base for a lot of the new features XUnit brings forward.
Note that XUnit is also installed via a NuGet package much like NUnit, which you can search for within Visual Studio. The packages I’ve used for this example are XUnitand XUnit.ConsoleRunner, though you also have the option of installing a GUI-based plugin for Visual Studio.
Much like the [TestCase] tag in NUnit, XUnit has its own solution to providing parameters to a test case. To do so we will be using the new[InLineData]tag and Theories.
In general, a test case that has no parameters (so it doesn’t rely on any changing data) is referred to as a Factin XUnit, meaning that it will always execute the same (so ‘Fact’ suits it pretty well). On the other hand, we have Theories, which refers to a test case that can take data directly from [InLineData]tags or even from an Excel spreadsheet
So with all these new fancy keywords in mind, let’s write a test in XUnit that uses a theory to test our bugs dodge ability:
This test covers both cases at once, where the bug dodges and survives, or doesn’t dodge and gets hit. Lovely!
Now, last step, lets run the XUnit test runner from the command line (note that much like NUnit, XUnit also has a GUI based visual studio plugin available for you to run tests with).
First you must make sure you are in your project’s root directory, just like NUnit (e.g. C:Users</span>yourUserNameDocumentsVisual Studio 2015Projects</span>YourProjectName) and then enter the following command in a new cmd window:
packagesxunit.runner.console.2.1.0toolsxunit.console.exe YourProjectNamebinDebug</span>YourProjectName.dll
Assuming everything is set up properly, the XUnit console runner will run all the tests in your project and let you know how your tests turned out.
Looks like our dodging tests passed!
Overall XUnit acts as the more contemporary version of NUnit, offering flexible and usable testing with a fresh coat of paint.In conclusion…
Regardless of which of the unit testing frameworks you use, you’re going to be getting all the basics. However, there are a few differences between them that I hope I’ve highlighted so you can choose the right one for your project. Whether it’s the convenience of Microsoft’s built in unit testing framework, the solid and well proven status of NUnit, or the modern take on unit testing that XUnit provides, theres always something out there that will give you exactly what you need!
Want to add an extra layer of protection for your code? Catch the errors that fall through the cracks with Raygun. Take a free trial here. -->
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 the IAccount 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 project AccountsTests.
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
https://diarynote.indered.space
The creation of unit tests is an important step in ensuring the quality of a project. In general, most public methods are tested, but what if you want to test a non-public part of the project? Putting all classes of your.Net project in public is not recommended. You can 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. Test Explorer is a handy feature of Visual Studio that allows you to run unit tests within a project, customize how they’re run, and interpret their output. Test Explorer allows you to manipulate the order that unit tests are run, create custom playlists to segment out which unit tests run, and run tests in various user-defined groups.
*Visual Studio Unit Test Mock
*Visual Studio Unit Test
*Visual Studio Unit Test Async
*Visual Studio Unit Test Framework
*Visual Studio Unit Test Project
*Visual Studio Unit Testing
When you find yourself (or your company) with more code than anyone could ever test by hand, what can you do? Well, unit testing has always been the perfect solution, as you can run tests that check more data than a person could in a day in a matter of milliseconds. So today I’ll take a look into a few popular C# unit testing frameworks and try them out first hand so you can choose which one best suits your project.
Unit tests can be run as often as you want, on as many different kinds of data as you want and with next to no human involvement beyond once the tests are written.
Not only that, but using code to test code will often result in you noticing flaws with your program that would have been very difficult to spot from a programmer’s viewpoint.Raygun lets you detect and diagnose errors and performance issues in your codebase with ease It takes minutes to add Raygun into your software. Be alerted to issues affecting end users and replicate problems 1,000x faster than using logs and incomplete information from users. Learn more and try Raygun free for 14 days. Popular C# unit testing frameworks
The unit testing frameworks I’ll be testing are:
*NUnit
*XUnit
*Built-in Visual Studio testing tools
All of these unit testing frameworks offer a similar end goal, to help make writing unit tests faster, simpler and easier! But there are still a few key differences between them. Some are more focused towards powerful complex tests, while others rank simplicity and usability as a higher priority. First up is Microsoft’s own built in Visual Studio unit testing tools
In most versions since 2005, Visual Studio has come with a built in testing framework supported by Microsoft. This framework certainly wins the most points for installation. Though if your copy of Visual Studio doesn’t come with it already included you are going to have to jump though a few hoops to get it going. (We wrote a review of the 2017 version of Visual Studio here.)
This framework is the simplest of the three, and uses an easy to understand method attribute structure (much like most testing frameworks) where you are able to add tags such as ‘[TestClass]’and ‘[TestMethod]’to your code in order to get testing.
Visual Studio even has a UI panel dedicated to visualizing your tests, which can be found under Test -> Windows -> Test Explorer.
Now before we dive into trying out this testing framework let’s introduce our example classes that need testing.
First we have a Raygun, which we can fireand recharge. The only thing we need to keep track of with our Raygun is it’s ammo, which can run out.
We also have a bug, which we can shootat with our Raygun. But this bug has the ability to dodgeour attempts to shoot it. If we shoot at a bug after it has just dodged, we will miss. Though if we hit the bug square on, it’s safe to assume that it will be dead.
These two classes are defined as follows:
Seems simple enough, but we need to make sure that our Rayguns and bugs behave as we want them to.
So then it’s time to write some unit tests! (We wrote about how to write robust unit tests in C# here.)
First up let’s try a simple situation where we want to shootat, and hit, a bug.What we would expect is that afterwards the bug will be dead, and the Raygun will still have a bit of juice left in it.
Well, let’s see if we are right:
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.
Since these tools are built for Visual Studio, running your tests from within Visual Studio is very simple.Just right click on any[TestMethod]tags as shown:
And would you look at that, the test passed. Looks like our Raygun can at least hit a stationary bug.
Of course this is only showing the bare basics of what Visual Studio’s testing tools can do.
Some other very useful tags you will surely be using are the [TestInitialize]and [TestCleanup]tags.These tags allow you to specify code that is run before(initialize) and after(cleanup) every individual test is run.
So if you want to reload your Raygun after every encounter like a stylish gunslinger, then this should do the trick:
Stylish.
While we are still talking about the Visual Studio testing tools I’ll quickly mention the [ExpectedException]tag, which is incredibly useful for when you want to deliberately cause an exception in your test (which you will certainly want to do at some point to make sure your program isn’t accepting data it shouldn’t).
Here’s a quick example of how you would write a test that results in an exception:
Don’t worry about the index out of bounds exception, thanks to the [ExpectedException]tag the exception will be treated as a success and your test will pass. On the contrary if the exception isn’t thrown then the test will fail. Anyway, it’s about time we moved on to some more testing platforms!
Overall the built in Visual Studio testing tools do exactly what they say on the box. They are simple, easy to use and handle all the basic testing functionality you would need. Plus if you’re already working in Visual Studio then they are already ready to use!Next up is arguably the most popular C# testing platform, NUnitVisual Studio Unit Test Mock
NUnit is an incredibly widely used tool for testing, and it serves as an excellent example of the open source unit testing frameworks. It’s a broad and powerful testing solution. In fact it’s what we use here at Raygun for the bulk of our unit testing.
NUnit is installed via a NuGet package, which you can search for within Visual Studio.The packages I’ve used for this example are NUnitand NUnit.ConsoleRunner, though you also have the option of installing a GUI-based plugin for Visual Studio.
NUnit uses a very similar attribute style system just like the visual studio testing tools, but now we will be referring to a [TestClass] as a [TestFixture],and a [TestMethod] as simply a [Test].
Now let’s go back to our Rayguns and bugs and have a look at another example, but this time using NUnit.
This time let’s make sure our dodgesand ammoare working properly, so let’s try and shoot a much more mobile bug:
Notice the new [TestFixture]and [Test]tags.
Now in order to run this test using NUnit, we need to seek the command line(unless of course you’ve chosen to install a GUI based plugin.)
First, you must make sure you are in your project’s root directory (e.g. C:Users</span>yourUserNameDocumentsVisual Studio 2015Projects</span>YourProjectName) and then enter the following command in a new cmd window:
packagesNUnit.ConsoleRunner.3.6.0toolsnunit3-console.exe YourProjectNamebinDebug</span>YourProjectName.dll
Assuming everything is set up properly, the NUnit console runner will run all the tests in your project and give you a nice little report on how things went:
Looks like our bug sure can dodge and our Raygun can certainly run out of ammo!
One feature of NUnit that makes it incredibly useful is the ability to include parameters in your tests!
This means that you can write a test case with arguments, then easily run the same test with a range of unique data. This removes the need to write unique test cases for every set of arguments you want to test.
Here’s a quick example test case we could use to make sure our Raygun was actually running out of ammoat the right time, in a much smarter way than before:
Excellent, with this one test case we were able to make sure a Raygun which has fired two shots still has ammo, while one that has fired three is empty. And thanks to the [TestCase]tag we were easily able to test a whole bunch of other values while we were at it!
Overall NUnit is an excellent testing framework, and as you delve deeper into what it can offer, it surely exceeds what Microsoft’s built in testing can offer.
Anyway, let’s look at our last testing framework, and our last attempt as shooting bugs with Rayguns!If you like the sound of Facts and Theories, then it’s time to look at XUnit
XUnit is an open source testing platform with a larger focus in extensibility and flexibility. XUnit follows a more community minded development structure and focuses on being easy to expand upon.
XUnit actually refers to a grouping of frameworks, but we will be focusing on the C# version.Other versions include JUnit, a very well known testing framework for Java.XUnit also uses a more modern and unique style of testing, by doing away with the standard [test] [testfixture] terminology and using new fancy tags like Factsand Theories.
NUnit and XUnit are actually quite similar in many ways, as NUnit serves as a base for a lot of the new features XUnit brings forward.
Note that XUnit is also installed via a NuGet package much like NUnit, which you can search for within Visual Studio. The packages I’ve used for this example are XUnitand XUnit.ConsoleRunner, though you also have the option of installing a GUI-based plugin for Visual Studio.
Much like the [TestCase] tag in NUnit, XUnit has its own solution to providing parameters to a test case. To do so we will be using the new[InLineData]tag and Theories.
In general, a test case that has no parameters (so it doesn’t rely on any changing data) is referred to as a Factin XUnit, meaning that it will always execute the same (so ‘Fact’ suits it pretty well). On the other hand, we have Theories, which refers to a test case that can take data directly from [InLineData]tags or even from an Excel spreadsheet
So with all these new fancy keywords in mind, let’s write a test in XUnit that uses a theory to test our bugs dodge ability:
This test covers both cases at once, where the bug dodges and survives, or doesn’t dodge and gets hit. Lovely!
Now, last step, lets run the XUnit test runner from the command line (note that much like NUnit, XUnit also has a GUI based visual studio plugin available for you to run tests with).
First you must make sure you are in your project’s root directory, just like NUnit (e.g. C:Users</span>yourUserNameDocumentsVisual Studio 2015Projects</span>YourProjectName) and then enter the following command in a new cmd window:
packagesxunit.runner.console.2.1.0toolsxunit.console.exe YourProjectNamebinDebug</span>YourProjectName.dll
Assuming everything is set up properly, the XUnit console runner will run all the tests in your project and let you know how your tests turned out.
Looks like our dodging tests passed!
Overall XUnit acts as the more contemporary version of NUnit, offering flexible and usable testing with a fresh coat of paint.In conclusion…
Regardless of which of the unit testing frameworks you use, you’re going to be getting all the basics. However, there are a few differences between them that I hope I’ve highlighted so you can choose the right one for your project. Whether it’s the convenience of Microsoft’s built in unit testing framework, the solid and well proven status of NUnit, or the modern take on unit testing that XUnit provides, theres always something out there that will give you exactly what you need!
Want to add an extra layer of protection for your code? Catch the errors that fall through the cracks with Raygun. Take a free trial here. -->
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 the IAccount 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 project AccountsTests.
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
https://diarynote.indered.space
コメント