Under the hood of database unit testing

In previous posts I have showed you how to create various kinds of database unit tests using Team Edition for Database Professionals. In this post I wanted to take you a little deeper and show you exactly how it works. With this knowledge, you’ll be able to customize your tests even further for complete power over the tests.


The way you have seen thus far for authoring database unit tests is using the database unit test designer shown below.



This designer allows you to create new tests methods, rename, and delete them. For each test method, it allows you to specify the test script SQL (which can be auto-generated for you) as well as the set of test conditions you wish to apply to this specific test. The test conditions are easily configured in the property browser.


This designer under the covers behaves much like the WinForms designer used to create Windows Forms applications. The designer generates and round-trips C#\VB code. It thus allows a user to not to have to worry about the underlying code and simply manipulate their tests from a simpler, more visual design surface. But of course, there will be times when you do want to see the generated code and maybe even modify it. Let’s take a look at what code is actually generated.


If you look at this below segment, you can see that the code that is generated is similar to regular unit tests that you would author using Team Test. The class has the appropriate TestClass attribute and the method has the appropriate TestMethod attribute.




The following is the code that is generated for a given test method:



And below is the associated code for that test method that is found in the InitializeComponent() method of the class.



The InitializeComponent code stores to local variables your test SQL as well as the test conditions and associated properties that you have applied to the specific test. The actual SQL is stored in the resource file found under the unit test cs file node. The code in the test method executes your SQL using ADO.NET and then executes each of the test conditions that you have defined. In addition, the generated code uses various settings saved to the app.config. For example, the connection strings are pulled from the app.config.


I hope this gives you a sense of what is actually happening when you author a database unit test. Since the generated code is exposed directly to you, this opens a world of possibility in terms of customization. Take a moment now to walk through the generated code and see if you can piece together what each statement is doing. In future posts I will explore many of these customization scenarios and show you exactly how you can add additional power to your tests.


Sachin Rekhi