Unit Testing Database Code
This lesson explains a layered testing strategy and how tSQLt isolates database objects for unit tests.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the layers of a database testing strategy.
- Identify which database objects benefit from unit tests.
- Explain how tSQLt fakes tables and spies on procedures.
A testing strategy for databases
A layered strategy runs fast checks often and slower checks less often, as the following steps show.
-
Build and code analysis
Every commit: the project build validates syntax and references, and code analysis flags risky patterns.
-
Unit tests
Every pull request: tests for functions, procedures, triggers and constraints run in an isolated database.
-
Integration tests
Every pull request or merge: the dacpac is deployed to a real or containerized database and end-to-end scenarios run, including the API.
-
Pre-production checks
Before release: a deploy report against staging, then smoke tests after deployment.
Layers of database testing
What to unit test
Good unit test targets are logic-bearing objects: functions that calculate values, procedures that validate input or change several tables, triggers, constraints that encode business rules, and security objects such as RLS predicates (for example, a test that a user sees only their own rows). Each test arranges known data, acts by calling the object and asserts the result. Tests should be independent of each other and of existing data.
A good unit test target?
Isolation with tSQLt
tSQLt is an open-source T-SQL unit testing framework. Tests are procedures in test classes (schemas). tSQLt.FakeTable replaces a table with an empty copy without constraints, so a test inserts only the rows it needs; tSQLt.SpyProcedure replaces a called procedure with a recorder; and assertions such as tSQLt.AssertEquals, tSQLt.AssertEqualsTable and tSQLt.ExpectException check results. Each test runs in a transaction that is rolled back, so tests leave no data behind.
EXEC tSQLt.NewTestClass 'SalesTests';
GO
CREATE PROCEDURE SalesTests.[test fnNetPrice applies the discount]
AS
BEGIN
DECLARE @actual decimal(10,2) = Sales.fnNetPrice(200.00, 15);
EXEC tSQLt.AssertEquals @Expected = 170.00, @Actual = @actual;
END;
GO
CREATE PROCEDURE SalesTests.[test usp_CreateOrder rejects unknown customer]
AS
BEGIN
EXEC tSQLt.FakeTable 'Sales.Customer'; -- empty, isolated copy
EXEC tSQLt.ExpectException @ExpectedErrorNumber = 50010;
DECLARE @id int;
EXEC Sales.usp_CreateOrder @CustomerID = 999, @OrderID = @id OUTPUT;
END;
GO
EXEC tSQLt.Run 'SalesTests';tSQLt installs objects that use SQL CLR, so it runs on SQL Server, including SQL Server containers, rather than on Azure SQL Database. Teams that deploy to Azure SQL Database run unit tests in a SQL Server container built from the same project, or write simpler test procedures that use THROW for assertions.
tSQLt procedures
Testing a procedure in isolation
A procedure calculates loyalty points from a customer's orders and calls another procedure that sends a notification. A unit test must check the points calculation without real orders in the database and without sending notifications. Which tSQLt features should the test use?
Use tSQLt.FakeTable on the Orders table and insert only the test's orders, use tSQLt.SpyProcedure on the notification procedure so it records the call instead of sending, run the procedure and assert the points with tSQLt.AssertEquals. Running the test against a copy of production data would make results depend on that data, and disabling the notification procedure would change the code under test.
Why does tSQLt not run on Azure SQL Database?
Show answer
It installs objects that use SQL CLR, which Azure SQL Database does not support; it runs on SQL Server, including containers.
Exam Tips
Remember for the exam
- Isolate tables: tSQLt.FakeTable; isolate called procedures: tSQLt.SpyProcedure.
- tSQLt tests roll back automatically after each run.
- tSQLt needs SQL CLR: run it on SQL Server or a SQL Server container.
- Layer the strategy: build, unit tests, integration tests, pre-production checks.