Introduction to unit and integration testing with tSQLt Elizabeth Noble elizabeth.a.noble@outlook.com @SQLZelda
Agenda Define database testing methods Setup tSQLt Create and run unit and integration tests
Purpose of Testing Unit testing - Test a single part of functionality Integration testing – Test interactions between more than one part of functionality
Advantages of Automated Testing Over time develop a collection of tests Confirm new or existing functionality did not break Find defects earlier in the development cycle
Downsides of Automated Testing Time consuming to create tests Can be difficult to design tests
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;
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
Create and Run Tests Determine what should be tested Design test to fail Write SQL to get test to succeed Repeat as needed
Demo
Conclusion Use tests to confirm functionality Install tSQLt in a development environment Think small when developing unit tests Test interactions with integration 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