Monday, April 22, 2013

Database driven C# Unit Testing with Visual Studio 2012

Recently I am engaged in C# develop, as a long time C/C++ and Java developer I get used to unit test mostly in Java with JUnit and suites of tools that working with it.  I was then investigate whats available for C# development platform.

I have found Visual Studio has their own unit testing platform/framework build in and it is very powerful.  It has a data drive feature the able to use a table to drive the test, so that it can use part of the whole table to test a method.  The trouble is most example are using MS SQL or XML as its example, but sadly none of my project is using MS SQL and some of the testing I require to utilize MySQL's data to test the unit.

Lucky after I did some search and get some understanding on how it picks up its data source.  I am now able to use MySQL or MS Access database to drive the test.

MS Access as unit test's datasource
Using MS Access is easy, since all the driver are the same the most examples out there.  Some trick that I found are:
1. Access database file can be accessed at the working (debugging) directory, you may want to create the database at the project directory then set the project to copy the database file to the debugging location.
2. The database is able to handle UNICODE, so I can now test my application with Chinese characters as the expected result(s).

Following is the setup attributes for using MS Access 2010:

        [TestMethod]
        [DataSource("System.Data.OleDb",


            "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=TestDB.accdb",
            "db_table", DataAccessMethod.Sequential)]

MySQL as unit test's datasource 
To use MySQL as datasource, you first need to install the MySQL Connector/Net to allow .Net to access the database.
        [DataSource("MySql.Data.MySqlClient",
            "server=localhost;userid=username;password=password;database=TestDB",
            "db_table", DataAccessMethod.Sequential)]


No comments:

Post a Comment