Unit testing using the Unit Test framework

Source: Internet
Author: User

Unit testing is intended to ensure that the code runs as expected by the programmer, often focusing on a lower level than other tests, to determine whether the underlying functionality of the code is consistent with expectations.

An important benefit of unit testing for the API framework is that testing introduces dependencies during the compilation phase, making it easier to determine whether changes to the code affect the contract that the API represents.

Unit test assemblies are typically separated from the code under test, which guarantees that unit tests are not included in the deployment of the application code because unit test code is not used in the production environment.

The easier it is for independent unit testing of code, the easier it is to maintain.

All tests should be autonomous and independent, and should be tested for expected behavior and error conditions.

Assume that the following content is required to be tested:

1 namespaceExtendedmath2 {3      Public Static classFunctions4     {5          Public Static intFibonacci (intfactor)6         {7             if(Factor <2)8             {9                 return(factor);Ten             } One             intx = Fibonacci (--factor); A             inty = Fibonacci (--factor); -             returnX +y; -         } the     } -}
View Code

The next step is to create the unit test validation Fibonacci implementation, which is called a test only after it is included in the standalone test project projects.

Create a unit test project, add a namespace reference to the above code, and add a reference at the top of the test class:

1 using Extendedmath; 2 using Microsoft.VisualStudio.TestTools.UnitTesting;
View Code

In order for Visual Studio to recognize a class that contains unit tests, you must assign a value to the TestClass attribute, and if you forget to add the TestClass attribute, you will not find the unit test method in the class. Unit tests need to be stored in a public class, so be sure to mark the class as public, the unit test method must be common and non-static, and there are no parameters and return values, in order to differentiate between unit test methods and normal methods, you need to use the TestMethod attribute. At this point we see the following code:

1 namespaceExtendedmath2 {3 [TestClass]4      Public classfunctionstest5     {6 [TestMethod]7          Public voidfibonaccitest ()8         {9         }Ten     } One}
View Code

Unit tests indicate a failure to Visual Studio by throwing an exception. Tests that do not throw exceptions are considered to be passed unless the test is for the ExpectedException attribute and the unit test framework defines the Assert object. Add code in the Fibonaccitest () method:

1 [TestMethod]2          Public voidfibonaccitest ()3         {4             Const intFACTOR =8;5             Const intexpected = +;6             intactual =ExtendedMath.Functions.Fibonacci (FACTOR);7 8 assert.areequal (expected, actual);9}
View Code

3 A mode is helpful when writing unit test methods--arrange, ACT, Assert. First set up the variable to schedule the test, then test the calling code, and finally assert that the calling code is consistent with the expected value. A relatively separate code snippet should be established for each a.

Use the TestInitialize attribute to create a method that will be executed one time before each unit test method of the current class executes. Similarly, TestCleanup is always executed immediately after each test execution. Similar to unit tests, methods that contain these attributes must be public and non-static, and have no parameters and return values. Run unit tests immediately after TestInitialize run and run TestCleanup immediately after unit test runs.

The ClassInitialize and ClassCleanup attributes are run only once in the current class, regardless of the number of times the unit tests are performed. The two methods are static and accept an TestContext instance as a parameter.

You can use ClassInitialize and ClassCleanup to control class-level operations, and for assembly-level operations you need to use the AssemblyInitialize and AssemblyCleanup features. For example, a method decorated with AssemblyInitialize is executed before any of the tests in the current assembly are executed, not just for tests in the current class. These methods must also be static and accept a parameter of type TestContext.

When there are common operations between multiple classes, you can consider using the assemblyinitialize and AssemblyCleanup attributes, but instead of calling the Initialize and purge methods for each class, use an assembly-level approach.

A common way to determine the success of a unit test is to compare the expected results with the actual results.

Assert.aresame/asser.arenotsame common usage is to ensure that the property returns the expected instance, or that the collection correctly handles the references, which are used to verify that the two parameter states are in fact pointing to the same object.

Typically, unit tests have a reference to a TestContext instance that is used to provide runtime functionality to the test, such as the details of the test itself, the various catalogs used, and methods to provide detailed information stored in the test results.

The best way to validate code behavior is to execute code with real data. Visual Studio provides the ability to automatically bind a data source as input for unit tests. Unit tests will run once for each data row.

How do I test the non-public members of a class? If you are writing a private function that is not publicly accessible and accessible only by other members of the internal, we want to test the method, but the test code does not have access to the private member, which is usually handled in 4 ways:

1. Change private members that need to be tested to public members
2. Change the private member that needs to be tested to an internal member and add the test assembly to the InternalsVisibleTo attribute of the original assembly
3. Ensure that private members that need to be tested are accessible through public members and then tested by those public members
4. Use in the test. NET reflection joins and calls directly those non-public members

Suppose you want to test the private data fields and methods of the following class:

1      Public classExample2     {3          PublicExample ()4         { }5         Private stringPassword ="Letmein";6         Private BOOLVerifyPassword (stringpassword)7         {8             return(string. Compare ( This. password, password,false) ==0);9         }Ten}
View Code

Visual Studio introduces the Privateobject class, which encapsulates the reflection code that allows access to non-public members in a very straightforward way. To use this class, you first need to create an instance of the class whose parameters are the type object of the class you want to process:

1 namespaceExplorations2 {3 [TestClass]4      Public classexampletest5     {6         PrivatePrivateobject Privateobject;7         Const stringPASSWORD ="Letmein";8 9 [TestInitialize]Ten          Public voidTestInitialize () One         { APrivateobject =NewPrivateobject (typeof(Example)); -         } -     } the}
View Code

The next step is to create the test:

1 namespaceExplorations2 {3 [TestClass]4      Public classexampletest5     {6         PrivatePrivateobject Privateobject;7         Const stringPASSWORD ="Letmein";8 9 [TestInitialize]Ten          Public voidTestInitialize () One         { APrivateobject =NewPrivateobject (typeof(Example)); -         } -  the [TestMethod] -          Public voidCompareprivatepassword () -         { -             stringPassword = (string) Privateobject.getfield ("Password"); + assert.areequal (PASSWORD, PASSWORD); -         } +  A [TestMethod] at          Public voidTestprivateverifypassword () -         { -             BOOLAccepted = (BOOL) Privateobject.invoke ("VerifyPassword", PASSWORD); - Assert.istrue (accepted); -         } -     } in}
View Code

Because Privateclass uses reflection, the invocation result must be converted from the generic object type to the correct type.

Privateobject is used to access instance members of a class, and if you want to access a non-public static member, you need to use the Privatetype class, which has an interface that is very similar to privateobject and encapsulates the reflection code.

The Visual Studio Unit testing feature fully supports code coverage, and code overrides automatically insert trace logic (the plug-in process) to monitor which code is executed during test execution. Its most important function is to discover the pieces of code that are not involved in the test.

One principle that explains the effectiveness of unit tests is that deleting any line of code will result in the failure of at least one unit test.

After you enable code coverage and select the assemblies you want to plug in, you run the tests, and you can browse the results of the overrides from the Code Coverage Results window:

100% of code coverage does not mean that the unit tests are sufficient, and that proper testing requires multiple tests of the same code using different data. Code coverage is a measure of the effectiveness of testing, but certainly not unique.

Use test impact analysis to explore which tests are affected by code changes after the code is modified, not just unit tests, but even those that were previously performed for a build.

Before you use test impact analysis, you must first use the Unit test framework within VS, store the source code in TFS Version control, and then enable the data collection feature when you run unit tests. If a unit test is running locally or through MTM (Microsoft Team Manager), you must upload the test results to TFS and associate it with a team build before you can test the impact analysis. There is not much to be introduced here.

Unit testing using the Unit Test framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.