Tuesday, April 21, 2009

Use DataSource in Unit Test

I had a unit test in C#, written to test one of the functions of my service. Considering best practices of testing like Boundary Value testing, there were number of data input which I had to consider to completely test the function. For doing that one of the ways is, instead of writing different tests with different type of inputs, we can classify the test with respect to passing tests and failing tests.

I created a test for passing input values and another test in which the Test had an Expected Exception. In both the cases I had wide range of data input. For this I used a CSV file for getting the input data. So for in a particular test, all the data combinations mentioned in the CSV will be executed.
For using a Data Source in a test we will have to perform the following steps.


1. Go to the Properties of the Test (Press F4 after selecting the Test in TestView)


2. Select the Data Connection String button
3. Then select the type of input file suitable to you (CSV or XML) In my case I used CSV




4. First Row of the CSV is automatically considered as header. (This needs to be taken care of while preparing the CSV)



5. Select Yes/No in the next dialog box if you wish to select this CSV to be added in deployment item and also get added to the solution. If you select Yes, the CSV will be added to the current project and also it will be added in the list of Deployment files in the LocaltestConfig.TestConfig file.


6. The Test will now look like

[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "DataDirectory\\CSV.csv", "CSV#csv", DataAccessMethod.Sequential), DeploymentItem("Test\\QA\\UnitTestProjectName\\CSV.csv"), TestMethod]
public void TestUsingDataSource()
{
}
7. For using the data in the test you will have to write TestContext.DataRow["Name"]
Note: The name you mention here should be exact to the header name given in the CSV.
The retrieved data from CSV can be converted to string by
Convert.ToString(TestContext.DataRow["Name"]).Trim();
That’s it. The test will be using the CSV whenever it runs now. The important thing to remember is whenever you run the test once from the test view, it will have individual runs inside it which will depend on the number of rows of the CSV.

4 comments:

Puneet Parakh said...

just passed by your blog.. must say c, c++ all are greek to me :-)

Bhavik Patel said...

Just like Investment Banking is to me :)

anjana said...

I am getting an unspecified error on the import page.. NOt sure why .. It does not even show me the finish page

Anonymous said...

Good example. I quickly had my UnitTest running.