Thursday, 28 April 2016

Testing Web Service

You can test Web services by calling Web methods from unit tests. Testing Web services is much like testing other code by using unit tests in that you can use Assert statements, and the tests produce the same range of results. However, the Microsoft.VisualStudio.TestTools.UnitTesting.Webnamespace of Team Edition for Testers provides attributes and methods specifically for testing Web services; they are described in Testing a Web Service Locally.
The following list describes two ways to test Web services with unit tests:
  • The Web service runs on an active Web server. There are no special requirements for testing a Web service that runs on a local or a remote Web server, such as IIS. To do this, add a Web reference and then call the Web methods of the Web service from your unit tests just as they would call the methods of a program that is not a Web service. For information about how to add a Web reference, see Add Web Reference Dialog Box. For information about how to create unit tests, see How to: Generate a Unit Test and How to: Author a Unit Test. For information about how to use a Web test to test a Web service, see How to: Create a Web Service Test.
  • The Web service is not hosted in an active Web server. As described in Testing a Web Service Locally, you can test a Web service that runs on your local computer and not in a Web server, such as IIS. To do this, you use an attribute provided by the Team System testing tools to start ASP.NET Development Server. This creates a temporary server at localhost that hosts the Web service that you are testing. For more information about ASP.NET Development Server, see Web Servers in Visual Web Developer.

Testing a Web Service Locally


This is the process for testing a Web service that runs on your local computer but not in IIS:
  1. Create the Web service on the local file system. For more information, see Walkthrough: Creating an XML Web Service Using Visual Basic or Visual C#.
  2. Generate unit tests against the Web service in the standard way for generating unit tests. For more information, see How to: Generate a Unit Test.
  3. Add the AspNetDevelopmentServerAttribute attribute to the unit test. The arguments for this attribute class point to the site of the Web service and name the server. For more information, see Ensuring Access to ASP.NET Development Server.
  4. Within the unit test, add a call to the TryUrlRedirection method to point the Web service object to the correct server. Verify that it returns true, and use and Assert statement to fail the test if the redirection fails. For more information, see Using the TryUrlRedirection Method.
  5. Call the Web service or exercise it in any other way that you feel is necessary to test it thoroughly. For an example of this, see Example Web Service Test Method.

Ensuring Access to ASP.NET Development Server

If the site of the Web service is on your local file system, it uses ASP.NET Development Server and it is not an IIS site. In this case, the process of generating unit tests starts an ASP.NET Development Server for the Web service and adds a Web reference to the test project.
The ASP.NET Development Server is temporary , and the Web reference would fail after the server is stopped. Team System testing tools solve this problem by providing the AspNetDevelopmentServer attribute. This attribute class has two constructors:
AspNetDevelopmentServerAttribute(string name, string pathToWebApp)
AspNetDevelopmentServerAttribute(string name, string pathToWebApp, string webAppRoot)

The following parameters are used with this attribute:
  • name is a user-defined name that is associated with the server.
  • pathToWebApp is the path on disk to the Web site you are testing.
  • webAppRoot is the virtual path at which the site appears on the server. For example, if webAppRoot is set to /WebSite1, the path to the site is HTTP://localhost:<port>/WebSite1. For the first constructor, the default is http://localhost:<port>/.
NoteNote
The parameters pathToWebApp and webAppRoot are used the same way with AspNetDevelopmentServerAttribute as they are for theAspNetDevelopmentServerHost attribute, which is used for ASP.NET unit tests.
When you mark a test with the attribute AspNetDevelopmentServerAttribute, an ASP.NET Development Server is started whenever the test is run. An entry that contains the URL of the site being tested is added to TestContext.Properties of the test class . The key for this entry is AspNetDevelopmentServer.<name>, where
<name> is the value held by the name argument of the attribute. This mechanism makes sure that the Web service is always available at an ASP.NET Development Server when the test is run and that the URL is known at run time.
To test a Web service this way, you could generate unit tests, or you could write a unit test by hand and mark it with this attribute. Hand authoring requires that you have a Web reference in place so that you can reference the type of the Web service in the code of your unit test. Before you add the Web reference, you must start an ASP.NET Development Server by right-clicking the Web service project and choosing View in Browser.

Using the TryUrlRedirection Method

After you have a Web reference, you can create an instance of the Web service object in your test code, but this might fail at run time because the reference points to the URL of an instance of ASP.NET Development Server that may no longer be running. To solve this problem, use theTryUrlRedirection method to modify the Web service object so that it points to the ASP.NET Development Server that was started specifically for the running unit test.
TryUrlRedirection is a static method of the WebServiceHelper class that returns a Boolean that indicates whether the redirection succeeded.
bool TryUrlRedirection(System.Web.Protocols.WebClientProtocol client, TestContext context, string identifier)
TryUrlRedirection takes three arguments:
  • client is the Web service object to be redirected.
  • context is the TestContext object for the class.
  • identifier is the user-defined name for the server to which the Web service object is being redirected.
After calling this method, if it succeeds, you can then call Web methods on the Web service object. In this way, the Web service is accessed through the ASP.NET Development Server that was started when you started the unit test. You can use multiple AspNetDevelopmentServer attributes on a single unit test to start multiple servers, as long as you give them different names.
Unit test generation does not automatically add the AspNetDevelopmentServer attribute or the TryUrlRedirection method call. You must add these entities yourself. Both the attribute and the method are in Microsoft.VisualStudio.TestTools.UnitTesting.Web. Therefore, you will probably need ausing or Imports statement, as shown in the following example.

Example Web Service Test Method

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using TestProject1.localhost;

[TestMethod]
[AspNetDevelopmentServer("HelloWorldServer",
 @"C:\Documents and Settings\user\My Documents\Visual Studio 2005\WebSites\WebSite1")]
public void HelloWorldTest()
{
     HelloWorldService target = new HelloWorldService();

     Assert.IsTrue( WebServiceHelper.TryUrlRedirection
                         (
                          target,
                          testContextInstance,
                          "HelloWorldServer"
                         ),
                   "Web service redirection failed."
                   );

     string expected = "Hello World";
     string actual;

     actual = target.HelloWorld();

     Assert.AreEqual(
                     expected,
                     actual,
                     "TestProject1.localhost.HelloWorldService.
HelloWorld did not return the expected value."
                     );
}

Data Driven Testing in .Net Based Application

Overview of Data-Driven Unit Tests

A data-driven unit test is a unit test that is run repeatedly for each row in a data source.
A common scenario for using data-driven unit tests is the use of multiple input values to test an API. Instead of writing multiple unit tests that call the API, each with a new set of inputs, or creating an array in a unit test and using looping code, you can instead write a single unit test method that exercises the API. You can then retrieve data from the rows of a database table, for example, to pass to successive calls of that test method.
You could use this technique to test an application that is used by different users, each of whom has a different role. For each user, one row in the data source would indicate the expected response, based on role. The test would then test the application by running functionality for each user and verify that the response produced matches the expected response.
Creating Data-Driven Unit Tests
You can create a data-driven unit test in either of two ways:

How to: Configure a Data-Driven Unit Test

You can configure data-driven unit tests in the following ways:
  • Set properties on the test using the Properties window. For more information, see the section "Setting Properties for Data-Driven Unit Tests."
  • In the source code for the unit test, provide a [DataSource] attribute, in which you specify the data that is required to access the data table. For more information, see Coding a Data-Driven Unit Test.
  • In the source code for the unit test, provide a [DataSource] attribute. But instead of using this attribute to supply the data-table access information, specify an entry from the microsoft.visualstudio.TestTools/dataSources section in the application-configuration file for the test assembly. This method gives you the flexibility to change the data-table access information without recompiling the unit test. For more information, see Walkthrough: Using a Configuration File to Define a Data Source.

Setting Properties for Data-Driven Unit Tests

You can configure a data-driven unit test by starting with any existing unit test—either generated or hand-authored—and setting specific properties on the test.

To configure a data-driven unit test

  1. Select the test in Test Manager window or Test View window.
  2. Press F4 to open the Properties window.
    The properties for the unit test are displayed in the Properties window.
  3. For the unit test, set the following properties.
    Data Connection String
To edit the Data Connection String property, click the property in the Properties window and then click the ellipsis (…). This opens the Choose Data Source dialog box, which lists several possible data sources, including ODBC, Microsoft SQL Server, and Microsoft Access. Choosing a data source opens a dialog box specific to the type of data source; you use this dialog box to configure the connection properties for the data source. When you have finished configuring the data connection, the connection string appears as the value for Data Connection String. This string is also stored as an attribute of the unit test method.

Data Provider Name
This value is set as a result of your setting the Data Connection String. Therefore, the Data Provider Name property is read-only in the Properties window. However, you can change the Data Provider Name value in an attribute of the unit test method.
Data Table Name
You can select a data table after you have established a connection to a data source. When you click the drop-down list in the values column of the Properties window, the tables in the connected database are listed. The table you select from this list is the table whose rows will be retrieved when the unit test is run. As with other properties such as Data Connection StringData Table Name is stored as an attribute of the unit test method.
Data Access Method
For the Data Access Method, select either Sequential or Random; the default value is Sequential. This setting represents the order in which records are retrieved from the table in the data source and is used when the unit test is run repeatedly.

Coding a Data-Driven Unit Test

A unit test functions as data-driven test if it has the attributes that a data-driven unit test requires. You can assign these attributes and their values either by using the Properties window or by adding the attributes directly to the test's code.
For more information on configuring a unit test as data-driven by editing its properties, see How to: Configure a Data-Driven Unit Test.
This topic describes how to code a unit test as a data-driven unit test, using the DataSource attribute and the TestContext class.

Using Data from a Data Source

When a data-driven unit test is running, data is retrieved from the rows of a data source. The data then is available to the running unit test through the DataRow and DataConnection properties of the TestContext class.
In the following example, DataRow is of the type DataRow, and LastName is the name of a valid column in the row associated with the current iteration of the data-driven test. 
TestContext.DataRow["LastName"]
While LastName refers to a column by name, you can also refer to columns by column number.
For each row in the table, any number of columns can be accessed. You can, for example, retrieve several columns of data at once, use them in a calculation, and then compare the result with a final column that contains an expected return value.

Coding a Data-Driven Unit Test

To create a data-driven unit test, you can start with either a unit test that you have created by hand or a generated unit test. For more information, see How to: Author a Unit Test and How to: Generate a Unit Test.
To configure your existing unit test, add attributes that define the data source you want it to use, the way you want that data to be accessed, and the table whose rows you want your test to use as input. For more information on configuring these attributes, see How to: Configure a Data-Driven Unit Test.
For example, the following code is from a data-driven unit test that uses data from the Northwind database.
[TestClass]
    public class TestClass
    {
        private TestContext m_testContext;
        public TestContext TestContext
        {
            get { return m_testContext; }
            set { m_testContext = value; }
        }
        [TestMethod]
        [DeploymentItem("FPNWIND.MDB")]
        [DataSource("System.Data.OleDb", "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=\"FPNWIND.MDB\"", "Employees", DataAccessMethod.Sequential)]
        public void TestMethod()
        {
            Console.WriteLine( "EmployeeID: {0}, 
LastName: {1}", TestContext.DataRow["EmployeeID"],  TestContext.DataRow["LastName"] );
        }
    }

The code within the test method in this example uses values from the LastName and EmployeeID columns in the "Employees" table of the data source. The test method accesses these values through a TestContext property, which is defined in the test class that contains the method.

Walkthrough: Using a Configuration File to Define a Data Source

This walkthrough illustrates how to use a data source defined in an app.config file for unit testing. You will learn how to create an app.config file that defines a data source that can be used by the DataSourceAttribute class. Tasks presented in this walkthrough include the following:
  • Creating an app.config file.
  • Defining a custom configuration section.
  • Defining connection strings.
  • Defining the data sources.
  • Accessing the data sources using the DataSourceAttribute class.

To add an app.config file to the project

  1. If your test project already has an app.config file, go to Define a Custom Configuration Section.
  2. Right-click your test project in the Solution Explorer, point to Add, and then click New Item.
    The Add New Item window opens.
  3. Select the Application Configuration File template and click Add.

Define Data Sources

The data sources section contains four attributes that are used by the test engine to retrieve data from a data source.
  • name defines the identity used by the DataSourceAttribute to specify which data source to use.
  • connectionString identifies the connection string created in the previous Define Connection Strings section.
  • dataTableName defines the table or sheet that holds the data to use in the test.
  • dataAccessMethod defines the technique for accessing data values in the data source.
In this section, you will define two data sources to use in a unit test.

To define data sources

  1. After the connectionStrings element, create a microsoft.visualstudio.testtools element. This section was created in Define a Custom Configuration Section.
  2. Within the microsoft.visualstudio.testtools element, create a dataSources element.
  3. Within the dataSources element, create two add elements.
  4. In the first add element, create the following attributes and values for a Microsoft Access data source:
The final app.config file should look similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
    </configSections>
    <connectionStrings>
        <add name="MyJetConn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\testdatasource.mdb; Persist Security Info=False;" providerName="System.Data.OleDb" />
        <add name="MyExcelConn" connectionString="Dsn=Excel Files;dbq=data.xls;defaultdir=.; driverid=790;maxbuffersize=2048;pagetimeout=5" providerName="System.Data.Odbc" />
    </connectionStrings>
    <microsoft.visualstudio.testtools>
        <dataSources>
            <add name="MyJetDataSource" connectionString="MyJetConn" dataTableName="MyDataTable" dataAccessMethod="Sequential"/>
            <add name="MyExcelDataSource" connectionString="MyExcelConn" dataTableName="Sheet1$" dataAccessMethod="Sequential"/>
        </dataSources>
    </microsoft.visualstudio.testtools>
</configuration>
Now that an app.config file has been defined, you will create a unit test that uses data located in the data sources that are defined in the app.config file. In this section, we will:
  • Create the data sources found in the app.config file.
  • Use the data sources in two test methods that compare the values in each data source.

To create a Microsoft Access data source

  1. Create a Microsoft Access database named testdatasource.mdb.
  2. Create a table and name it MyDataTable in testdatasource.mdb.
  3. Create two fields in MyDataTable named Arg1 and Arg2 using the Number data type.
  4. Add five entities to MyDataTable with the following values for Arg1 and Arg2, respectively: (10,50), (3,2), (6,0), (0,8) and (12312,1000).
  5. Save and close the database.
  6. Change the connection string to point to the location of the database. Change the value of Data Source to reflect the location of the database.

To create a Microsoft Excel data source

  1. Create a Microsoft Excel spreadsheet named data.xls.
  2. Create a sheet named Sheet1 if it does not already exist in data.xls.
  3. Create two column headers and name them Val1 and Val2 in Sheet1.
  4. Add five entities to Sheet1 with the following values for Val1 and Val2, respectively: (1,1), (2,2), (3,3), (4,4) and (5,0).
  5. Save and close the spreadsheet.
  6. Change the connection string to point to the location of the spreadsheet. Change the value of dbq to reflect the location of the spreadsheet.

To create a unit test using the app.config data sources

  1. Add a unit test to the test project.
    For more information, see How to: Author a Unit Test.
  2. Replace the auto-generated contents of the unit test with the following code:
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace TestProject1
    {
         [TestClass]
        public class UnitTest1
        {
            private TestContext context;
    
            public TestContext TestContext
            {
                get { return context; }
                set { context = value; }
            }
    
            [TestMethod()]
            [DeploymentItem("MyTestProject\\testdatasource.mdb")]
            [DataSource("MyJetDataSource")]
            public void MyTestMethod()
            {
                int a = Int32.Parse(context.DataRow["Arg1"].ToString());
                int b = Int32.Parse(context.DataRow["Arg2"].ToString());
                Assert.AreNotEqual(a, b, "A value was equal.");
            }
    
            [TestMethod()]
            [DeploymentItem("MyTestProject\\data.xls")]
            [DataSource("MyExcelDataSource")]
            public void MyTestMethod2()
            {
                Assert.AreEqual(context.DataRow["Val1"], context.DataRow["Val2"]);
            }
        }
    }
    
  3. Examine the DataSource attributes. Notice the setting names from the app.config file.
  4. Build your solution and run MyTestMethod and MyTestMethod2 tests.
Deploy items like data sources so that they are accessible to the test in the deployment directory. For more information, see Test Deployment.

Wednesday, 27 April 2016

Different Test Attribute in .Net Based Application and Data Driven Testing

We use different test attributes, to run our test , based on priority, categorization , Description , running test multiple times with different set of data and so on...

For Assemblies:


AssemblyInitialize and AssemblyCleanup are called right after your assembly is loaded and right before your assembly is unloaded.
For classes
ClassInitialize and ClassCleanup are called right after your class is loaded and right before your class is unloaded.
For test methods

Attributes Used to Identify Test Classes and Methods

Every test class must have the TestClass attribute, and every test method must have the TestMethod attribute. For more information, see Structure of Unit Tests.

Assert Classes and Related Exceptions

Unit tests can verify specific application behavior by their use of various kinds of Assert statements, exceptions, and attributes. For more information, see Using the Assert Classes.
   This attribute is used to test whether an expected exception is thrown. The test method will pass if the expected exception is thrown. The test will fail if the thrown exception inherits from the expected exception.

        [TestMethod()]
        [ExpectedException(typeof(System.DivideByZeroException))]
        public void DivideTest()
        {
            DivisionClass target = new DivisionClass();
            int numerator = 4;
            int denominator = 0;
            int actual;
            actual = target.Divide(numerator, denominator);
        }

The TestContext Class

The properties of the test context class store information about the current test run. For example, the TestContext.DataRow and TestContext.DataConnection properties contain information that is used by the test for data-driven unit testing.
You use the TestContext class in unit tests for any of several purposes. These are its most frequent uses:
  • In any unit test, because the TestContext class stores information that is provided to unit tests, such as the path to the deployment directory.
  • In unit tests to test Web services that run on ASP.NET Development Server. In this case, TestContext stores the URL of the Web service. 
  • In ASP.NET unit tests, to obtain access to the Page object. 
  • In data-driven unit tests, the TestContext class is required because it provides access to the data row.

Attributes for Identifying and Sorting Tests

The following attributes and the values assigned to them appear in the Visual Studio Properties window for a particular test method.
These attributes are not meant to be accessed through the code of the unit test. Instead, they affect the ways the unit test is used or run, either by you through the IDE of Visual Studio, or by the Team System test engine.
For example, some of these attributes appear as columns in the Test Manager window and Test Results window, which means you can use them to group and sort tests and test results.
One such attribute is TestPropertyAttribute, which you use to add arbitrary metadata to unit tests. For example, you could use it to store the name of a test pass that this test covers, by marking the unit test with [TestProperty("TestPass", "Accessibility")]. Or to store an indicator of the kind of test it is: [TestProperty("TestKind", "Localization")]. The property you create by using this attribute, and the property value you assign, are both displayed in the Visual Studio Properties window under the heading Test specific.
Used to specify deployment items such as files or directories for per-test deployment.
This attribute can be specified on a test method. There can be multiple instances of this attribute to specify more than one item. The item path can be absolute or relative. Relative paths are relative to the RelativePathRoot setting found in the .testrunconfig file.
The following examples demonstrate different usage of the DeploymentItemAttribute:
  • [DeploymentItem("file1.xml")]    Deploys an item named file1.xml located at the RelativeRootPath. The file is deployed to the deployment root directory.
  • [DeploymentItem("file2.xml", "DataFiles")]    Deploys an item named file2.xml located at the RelativeRootPath. The file is deployed to the DataFiles subdirectory of the deployment root directory.
  • [DeploymentItem("C:\\MyDataFiles\\")]    Deploys all items and directories found within the MyDataFiles directory. This does not create the MyDataFiles directory underneath the deployment directory. All files and directories within MyDataFiles will be deployed to the deployment root directory. To copy the entire MyDataFiles directory structure, you must specify MyDataFiles as an output directory.
  • [DeploymentItem("%myDir%\myFile.txt")]    Deploys the file myFile.txt if that file exists in the directory to which %myDir% resolves.
        [TestMethod()]
        [DeploymentItem("testFile1.txt")]
        public void ConstructorTest()
        {
            // Create the file to deploy
            Car.CarInfo();
            string file = "testFile1.txt";
            // Check if the created file exists in the deployment directory
            Assert.IsTrue(File.Exists(file), "deployment failed: " + file +
                " did not get deployed");
        }

Conclusion: If we want to access any file like excel, csv , xml ... we can define in
"DeploymentItem" attribute , after running the test it will copy into deployment directory
, we can use those file through code or we can define relative path in testrunconfig  file. 
   [TestMethod()]
   [HostType("ASP.NET")]
   [UrlToTest("http://localhost:1371/webSite12")]
   [AspNetDevelopmentServerHost("d:\\MyWebSite", "/MyWebSiteRoot")]
   public void ConstructorTest()
    { 
      object target = TestProject1.Class1Accessor.CreatePrivate();
      Assert.Inconclusive("TODO: Implement code to verify target");
    }

Test Configuration Classes

Provides access to a TestConfigurationSection that represents the microsoft.visualstudio.testtools section in an app.config file.

Attributes Used for Generating Reports

The attributes in this section relate the test method that they decorate to entities in the project hierarchy of a Team Foundation Server team project. For more information, see How to: Enable Reporting of Test Results.

Classes Used with Private Accessors

As described in How to: Test a Private Method and How to: Regenerate Private Accessors, you can generate a unit test for a private method. This generation creates a private accessor class, which instantiates an object of the PrivateObject class. The PrivateObject class is a wrapper class that uses reflection as part of the private accessor process. The PrivateType class is similar but is used for calling private static methods instead of calling private instance methods.
How to: Group and Run Automated Tests Using Test Categories
Test categories let you run groups of tests based on their assigned categories without the requirement to maintain test lists. A test category is a test method attribute that you can assign to one or more tests.
You can use logical operators with test categories to run tests from multiple categories together or to limit the tests that you run to tests that belong to multiple categories. Also, test categories are easy to add as you create your test methods and you do not have to maintain test lists after you have created your test methods.

Requirements

  • Visual Studio Enterprise, Visual Studio Test Professional

Creating and Assigning Test Categories

To manually add test categories to a test

  1. In your unit test project, or coded UI test project in Solution Explorer, open the file that contains the unit test, and then locate the unit test method that you want to change.
  2. Directly above the test method declaration, add a [TestCategory()] attribute for each test category that you want to assign to the test. Separate each attribute by using a comma.
  3. Add the category name enclosed in parentheses to each [TestCategory()] attribute. The following example is a method with three Test Categories assigned to it named "Nightly", "Weekly", and "ShoppingCart":
[TestCategory("Nightly"), TestCategory("Weekly"), TestCategory("ShoppingCart"),
 TestMethod()]
public void DebitTest()
{
}
Running Tests by Categories
When you run tests from the command line, you can also use logical operators & (AND), | (OR) and !(NOT) to select the tests to run based on the categories assigned to the tests.

To run test using categories from the command-line

  1. Open a Visual Studio command prompt. (Go to Start, All Programs, Microsoft Visual Studio, Visual Studio Tools, Developer Command Prompt.)
  2. By default, the Visual Studio command prompt opens to the following folder:
    <drive letter>:\Program Files\Microsoft Visual Studio 12.0\VC
  3. Either change the directory to the location in your solution folder where the test container is located, typically the test project's .dll file, or, when you run the MSTest.exe program in step 3, specify a full or relative path for the test container.
    To identify your solution folder, first identify the Visual Studio Projects folder. To do this, choose Options on the Tools menu in Visual Studio, and then choose Projects and Solutions. Under Visual Studio projects location, you see a path such as the following:
    <drive letter>:\Documents and Settings\<user name>\My Documents\Visual Studio\Projects
    Your solution folder is typically a child of this Projects folder, such as the Bank folder in the following example:
    <drive letter>:\Documents and Settings\<user name>\My Documents\Visual Studio\Projects\Bank
  4. To run tests that are assigned to the "Nightly" category, run the VSTest.Console.exe using the /TestCaseFilter option, or from MSTest.exe by using the /testcontainer and the /category options:
    VSTest.Console.exe
    Vstest.console.exe myTestProject.dll /TestCaseFilter:TestCategory=Nightly
    MSTest.exe
    mstest /testcontainer:MyTestprojectName.dll /category:"Nightly"
    The results and summary are displayed in the command prompt window.
Note:  You can use either AND or OR in your expression to select categories of tests, but not both in the same expression. Use in above command only or while creating build definition in TFS for CI setup.
RollBack attribute is used in MBUnit and NUnit framework for database testing

Few Important Assertion

List<object> itemList2 = new List<object>() { new AnObject() { SomeValue = 2 }, new AnObject() { SomeValue = 1 } };

CollectionAssert.AreEquivalent(itemList1, itemList2);

IsSubsetOf/IsNotSubsetOf
This assertion verifies that the first parameter (the subset) is contained in the second parameter’s collection (the superset).
Note that the subset test does not test for order or sequence—it simply tests whether the items in the subset list are contained in the superset. 

String Assertions
These methods are implemented in the Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert class:
? Contains
? Matches/DoesNotMatch
? StartsWith/EndsWith

The Contains method asserts that the subset (note that this is the second parameter) is contained in the string (the first parameter). 
For example, this test passes

 [TestMethod] 
public void SubsetTest() 
{
string subset = "abc"; string superset = "1d2c3b4a"; 
CollectionAssert.IsSubsetOf(subset.ToCharArray(), superset.ToCharArray());
 }

[TestClass] 
public class StringTests
 {
 [TestMethod] public void ContainsTest() 

string subset = "abc"; string superset = "123abc456";
 StringAssert.Contains(superset, subset);
}

}

Matches/DoesNotMatch
This method asserts that the string (the first parameter) matches the regex pattern provided in the second parameter.

StartsWith/EndsWith

This method asserts that the string (the first parameter) either starts with or ends with another string (the second parameter).

Accessign CSV file in Test Code:


[TestClass] 
public class DataSourceExamples
 { 
public TestContext TestContext { get; set; }

[TestMethod] 
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "C:\\temp\\csvData.txt", "csvData#txt", DataAccessMethod.Sequential)] 
public void CsvDataSourceTest()
 { 
int n = Convert.ToInt32(TestContext.DataRow["Numerator"]); 
int d = Convert.ToInt32(TestContext.DataRow["Denominator"]); int r = Convert.ToInt32(TestContext.DataRow["ExpectedResult"]); Debug.WriteLine("n = " + n + " , d = " + d + " , r = " + r); 
}
}

XML Data Source
Given an XML file such as:
an example of using an XML data source for a unit test is:
Note that other than the data source attribute parameters, the test code is the same.
Database Data Source
A database table can also be used as the data source. Given a table such as:
Figure 15: Database Table as a Data Source

and data:
 <Data>
 <Row Numerator = "10" Denominator = "5" ExpectedResult = "2"/>
 <Row Numerator = "20" Denominator = "5" ExpectedResult = "4"/> 
<Row Numerator = "33" Denominator = "3" ExpectedResult = "11"/>
 </Data>

 [TestMethod] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "C:\\temp\\xmlData.xml", "Row", DataAccessMethod.Sequential)] public void XmlDataSourceTest() { int n = Convert.ToInt32(TestContext.DataRow["Numerator"]); int d = Convert.ToInt32(TestContext.DataRow["Denominator"]); int r = Convert.ToInt32(TestContext.DataRow["ExpectedResult"]); Debug.WriteLine("n = " + n + " , d = " + d + " , r = " + r); }

Accesign Sql Server database:


[TestMethod] [DataSource("System.Data.SqlClient", "Data Source=INTERACX-HP;Initial Catalog=UnitTesting;Integrated Security=True", "DivideTestData", DataAccessMethod.Sequential)] public void XmlDataSourceTest() { int n = Convert.ToInt32(TestContext.DataRow["Numerator"]); int d = Convert.ToInt32(TestContext.DataRow["Denominator"]); int r = Convert.ToInt32(TestContext.DataRow["ExpectedResult"]); Debug.WriteLine("n = " + n + " , d = " + d + " , r = " + r); 
}


See Data Driven Testing in next post... 
Happy Reading   :)
Help Link: https://msdn.microsoft.com/en-us/library/ms243147(vs.80).aspx