Making Your List and Checking It Twice Unit Testing with tSQLt Elizabeth Noble elizabeth.a.noble@outlook.com @SQLZelda
Agenda What is unit testing How to setup tSQLt Create and run unit tests
Purpose of Unit Testing Test a single part of functionality Confirmation that functionality works New development Existing bugs
Advantages of Unit Testing Over time develop a collection of unit tests Confirm existing functionality did not break Find defects earlier in the development cycle
Downsides of Unit Testing Time consuming to create unit tests Can be difficult to design unit tests Does not test interactions with other parts of the system
How to Setup tSQLt Download tSQLt http://tsqlt.org/downloads/
How to Setup tSQLt CLR must be enabled Set database to TRUSTWORTHY EXEC sp_configure 'clr enabled', 1; RECONFIGURE; Set database to TRUSTWORTHY ALTER DATABASE < database name > SET TRUSTWORTHY ON;
How to Setup tSQLt Run tSQLt scripts Run the tSQLt.Class.sql http://tsqlt.org/user-guide/quick-start/#InstallToDevDb
How to Setup tSQLt Setup shortcut to run tSQLt Open SQL Server Management Studio Tools -> Options -> Keyboard -> Keyboard Shortcuts Shortcut: CTRL + 0 Stored procedure: EXECUTE <database name>.tSQLt.RunAll;
Create and Run Unit Tests Determine what should be tested Design unit test to fail Write SQL to get unit test to succeed Repeat as needed
Set up tSQL NewTestClass – creates a schema to group unit tests test – begin stored procedure names NewTestClass – creates schema that lumps all units tests and related objects FakeTable – makes a copy of the table; if it is not used, IDENTITY column may be incremented SpyProcedure –not used to test current stored procedure, used to run a stored procedure in a stored procedure test stored procedure - Stored procedure must begin with "test" at the beginning to be run as a unit test
Creating tSQL unit tests FakeTable – allows tests to be run on a copy of the actual table SpyProcedure – runs a copy of a stored procedure AssertEqualsTable – compares table results of actual versus expected NewTestClass – creates schema that lumps all units tests and related objects FakeTable – makes a copy of the table; if it is not used, IDENTITY column may be incremented SpyProcedure –not used to test current stored procedure, used to run a stored procedure in a stored procedure test stored procedure - Stored procedure must begin with "test" at the beginning to be run as a unit test
Demo
Conclusion Use unit tests to confirm functionality Install tSQLt in a development environment Think small when developing unit tests Design units tests to fail to avoid false positives
Additional Topics tSQLt - http://tsqlt.org/user-guide/quick-start/#InstallToDevDb Other options SQL Test - http://www.red-gate.com/products/sql-development/sql-test/ MSDN - https://msdn.microsoft.com/en-us/library/aa833283(v=vs.100).aspx SQL Cop - http://sqlcop.lessthandot.com/ Related topics Source control
Questions