Is there a way to create simple unit tests for SQL queries in SSMS? I’m fairly new to T-SQL & SSMS, but I’d like to try to carry some of my old TDD habits into this arena, if possible.
So, for example, when I write the DDL to create complex functions and what-not, I’d like to have some way to include a unit test that (upon failure) would actually cause the output panel to display an error message upon execution. (This would be analagous to “breaking the build” in a normal programming environment.)
Currently, when I write a function that is syntactically correct, then hit F5 to execute it, the output message is:
Command(s) completed successfully.
What I am looking for is some simple SQL trick to simulate basic red-light/green-light test cases. So I would write a series of test-statements that would pass only if my user-defined function is operating as intended. Otherwise an error message would be displayed, such as:
Msg 207, Level 16, State 1, Line 2
Invalid statement.
which would allow me to jump immediately to the failing test and see what I did wrong.
I don’t expect there to be anything “built-in” for this, but is there some way I can “fake it”?
Update: I just learned you can throw exceptions in SS2012, which I’m sure I could use for just this purpose, but unfortunately I’m stuck with SS2008 for now. Is there anything comparable in SS2008?
These are the 2 frameworks I can recomend
T.S.T.
http://tst.codeplex.com/
Testing SQL Server Code with TST
http://www.infoq.com/articles/tst-sql-server
tSQLt
http://tsqlt.org/
SQL Test (runner for tSQLt)
http://www.red-gate.com/products/sql-development/sql-test/
Update 1
Reading your answer maybe you find the following dump useful.
TRY CATCH was introduced with SQL Server 2005 (and for this reason one should never look at someting older then 2005). You can actualy (re)throw an exception using a stored procedure mentioned in my dump, including the line number. In SQL Server 2012 they (finaly!) introduced throw as you mention makeing Tsql a robust language after 14 years.
So here is my dump, I need to clean it up some day so Its more copy paste friendly.