Lesson 1 of 2 Database Testing

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.

  1. Build and code analysis

    Every commit: the project build validates syntax and references, and code analysis flags risky patterns.

  2. Unit tests

    Every pull request: tests for functions, procedures, triggers and constraints run in an isolated database.

  3. 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.

  4. Pre-production checks

    Before release: a deploy report against staging, then smoke tests after deployment.

Put in order

Layers of database testing

Exam skills 2.3.1

Put the testing layers in order, from the most frequent to the last before release.

Log in to try this activity Interactive activities are free with an account.

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.

Sort into groups

A good unit test target?

Exam skills 2.3.1

Decide whether each object is a good unit test target.

Log in to try this activity Interactive activities are free with an account.

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.

Match the pairs

tSQLt procedures

Exam skills 2.3.1

Match each tSQLt procedure with what it does.

Log in to try this activity Interactive activities are free with an account.
Worked example

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.

Check yourself

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.