How to data bind a Visual Studio 2013 Coded UI Test

Problem

I need to run the same Coded UI Test with different data.

Solution

Data bind your Coded UI Test.  To data bind a test in Visual Studio you just need access to the data source and add attributes to the test.

For this example we are going to use a simply CSV file.  So add a new text file to your project with a CSV extension. Create a comma delimited file of the desired data.  Make sure when you save it you first select “Advanced Save Options” from the File menu and select “Unicode (UTF-8 without signature) – Codepage 65001” before you save the file. Now right click on the item in Solution Explorer and select Properties. From the Properties window change the “Copy to Output Directory” to “Copy always”.

 

To your test you will need to add two attributes.  The first is the DeploymentItem attribute. This attribute takes a single string argument of the name of the CSV file. The second attribute is the DataSource attribute.  This attribute is where you define the class used to read the data, what table to read from and how the data should be accessed. 

For a CSV file the first argument will be “Microsoft.VisualStudio.TestTools.DataSource.CSV” which identifies the correct class to use to load the CSV file.  Next we need to let the test know where to find the data with “|DataDirectory|\\data.csv”.  Then we have to identify the table to read the data from with “data#csv”. Finally we have to give it an access method “DataAccessMethod.Sequential”.  The final attribute will look like this:

[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\data.csv", "data#csv", DataAccessMethod.Sequential)]

With the attributes in place you can now use the DataRow property of the TestContext to access the columns in your CSV for example:

TestContext.DataRow["FirstName"].ToString();

Good luck.

Comments are closed