The current time is

Tuesday, November 25, 2008

Writing a data-driven unit test

This was a really cool investigation…

It's all about one having a unit test case and it is required to run it using some number of data… An "easy" way out of this could be creating the same unit test case with different parameters every time. However, if one has enormous amount of data that should be tested on a specific method, he can create a unit test case and bind to it a datasource that is used by this test case.

Please follow the steps below:

  1. Create a new test Project (File New Test Project)
  2. Create a new method into the default class being created (Let us name it: TestTrimTexts())
  3. Above this method, you should write the code [TestMethod]
  4. To identify the datasource that would be used by this test method, you should write this line of code: [DataSource("System.Data.SqlClient", "Data Source=.\\OfficeServers;Initial Catalog=master;Integrated Security=SSPI;", "spt_values", DataAccessMethod.Sequential)]

    This instructs the CLR to use the table "spt_values" using the connection string "Data Source=.\\OfficeServers;Initial Catalog=master;Integrated Security=SSPI;" and the provider "System.Data.SqlClient". It also mentions that the data should be used sequentially.

    The most important part comes last, reading the data from the datasource just defined in the previous steps. You should add this pieace of code:


    Afterwards, inside the test method, TestTrimTexts(), you should use the TestContext.DataRow["name"] where it will contain data fetched from the datasource specified, the column named "name", in this case.

    Enjoy it then :)

    Notes: There is an overload for step number 4. Check the screen shot below:


    This overload had a small problem with me since it used data from the datasource randomly and this caused me to get frightened while debugging… I wasn't able to trace it with ease :)

References:

  1. http://msdn.microsoft.com/en-us/library/ms182528(VS.80).aspx
  2. http://msdn.microsoft.com/en-us/library/ms182527(VS.80).aspx
  3. http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testcontext.datarow(VS.80).aspx

No comments:

Post a Comment