KEMBAR78
Tutorial 4 Unit Test Start2021 | PDF | Unit Testing | Systems Architecture
0% found this document useful (0 votes)
25 views10 pages

Tutorial 4 Unit Test Start2021

The document provides an overview of unit testing, emphasizing its importance in ensuring code quality through discrete testable behaviors. It explains how to create unit test projects and methods in Visual Studio, including using the Test Explorer to run tests and view results. Additionally, it covers writing tests using the AAA pattern and the ability to analyze code coverage to assess the effectiveness of unit tests.

Uploaded by

Dashpitkach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views10 pages

Tutorial 4 Unit Test Start2021

The document provides an overview of unit testing, emphasizing its importance in ensuring code quality through discrete testable behaviors. It explains how to create unit test projects and methods in Visual Studio, including using the Test Explorer to run tests and view results. Additionally, it covers writing tests using the AAA pattern and the ability to analyze code coverage to assess the effectiveness of unit tests.

Uploaded by

Dashpitkach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Part 1: Unit Test Basics

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. When you use Visual Studio Enterprise, you can run tests
automatically after every build.

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.

Create unit test projects and test methods


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.

FizzBuzz
int main()

for(int i=1;i<=100;i++){

if((i%3 == 0) && (i%5==0))

cout<<"FizzBuzz\n";

else if(i%3 == 0)

cout<<"Fizz\n";

else if(i%5 == 0)

cout<<"Buzz\n";

else

cout<<i<<"\n";

return 0;

}
Extra

Generate unit test project and unit test stubs

1. From the code editor window, right-click and choose Create Unit Tests from
the context menu.

2. 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.

3. The unit test stubs are created in a new unit test project for all the
methods in the class.
Create your 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:

4. On the File menu, choose New and then choose Project (Keyboard Ctrl +
Shift + N).
5. On 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.
6. To use one of the Microsoft unit test frameworks, choose Unit Test
Projectfrom 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 .
Warning

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.

7. 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:


a. Select the project in Solution Explorer.
b. On the Project menu, choose Add Reference.
c. 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


the AccountInfo class in the BankAccount project
 CheckingAccountTests class contains the unit test methods
for CheckingAccount 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:
C#Copy

[TestMethod]
public void Withdraw_ValidAmount_ChangesBalance()
{
// arrange
double currentBalance = 10.0;
double withdrawal = 1.0;
double expected = 9.0;
var account = new CheckingAccount("JohnDoe", currentBalance);
// act
account.Withdraw(withdrawal);
double actual = account.Balance;
// assert
Assert.AreEqual(expected, actual);
}

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Withdraw_AmountMoreThanBalance_Throws()
{
// arrange
var account = new CheckingAccount("John Doe", 10.0);
// act
account.Withdraw(20.0);
// assert is handled by the ExpectedException
}

Note that Withdraw_ValidAmount_ChangesBalance uses an


explicit Assert statement to determine whether the test method passes or fails,
while Withdraw_AmountMoreThanBalance_Throws uses
the ExpectedException attribute to determine the success of the test method.
Under the covers, a unit test framework wraps test methods in try/catch
statements. In most cases, if an exception is caught, the test method fails and
the exception is ignored. The ExpectedException attribute causes the test
method to pass if the specified exception is thrown.

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.
As you run, write, and rerun your tests, the default view of Test Explorer
displays the results in groups of Failed Tests, Passed Tests, Skipped
Tests and Not Run Tests. You can choose a group heading to open the view that
displays all them tests in that group.

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 choose Run to choose a subset
of tests to run. After you run a set of tests, a summary of the test run appears
at the bottom of the Test Explorer window. Select a test to view the details of
that test in the bottom pane. Choose Open Test from the context 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.

Run tests after every build

Warning

Running unit tests after every build is supported only in Visual Studio
Enterprise.
To run your unit tests after each local build, choose Test on the standard
menu, choose Run Tests After Build on the Test Explorer toolbar.

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. 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 Tests on the Visual
Studio menu and then choose Analyze code coverage.
Coverage results appear in the Code Coverage Results window.

You might also like