Are you looking for a way to test your T-SQL code inside SQL Server? Look no further! The tSQLt framework is here to help. Developed by Sebastian Meine and Dennis Lloyd, tSQLt is a free unit testing framework designed specifically for database code in SQL Server.
Installing tSQLt is a breeze. Simply download the latest .zip file from the tsqlt.org website and extract it to your machine. Inside the extracted files, you’ll find the tsqlt.class.sql file, which is the only file you need for the framework. Before installing, make sure to enable the CLR and the Trustworthy setting in SQL Server. Once these properties are enabled, you can install the framework by executing the tsqlt.class.sql file.
Now that you have tSQLt installed, let’s write our first test. Tests in tSQLt are written as stored procedures inside test classes. To create a test class, use the EXEC tsqlt.NewTestClass
command. For example, to create a test class named “TestSample”, you would execute EXEC tsqlt.NewTestClass @ClassName = N'TestSample'
.
Once you have a test class, you can start writing tests. Tests are simple stored procedures that exist within the test class schema. Let’s say we want to test a stored procedure named “spDouble” that doubles the value of an input parameter. We can create a test for this by writing a stored procedure inside the test class. Here’s an example:
CREATE PROCEDURE [TestSample].[test spDouble Calculation]
AS
BEGIN
-- assemble
DECLARE
@param INT,
@expected INT,
@actual INT;
SET @param = 5;
SET @expected = 10;
-- Act
EXEC @actual = spDouble @param;
-- assert
EXEC tSQLt.AssertEquals @Expected = @expected, @Actual = @actual,
@Message = N'The calculation is incorrect.';
END;
In this test, we first set up the environment by declaring variables and assigning values. We then execute the stored procedure we want to test and finally assert that the expected value is equal to the actual value returned by the stored procedure.
Before running the test, we need to create the “spDouble” stored procedure. Here’s an example of how to create it:
CREATE PROCEDURE spDouble
@input int
AS
BEGIN
RETURN @input * 2;
END
GO
Now we can execute the test using the EXEC tsqlt.Run
command. Make sure to include the class and test name to run the test. For example, to run the “test spDouble Calculation” test in the “TestSample” class, you would execute EXEC tsqlt.Run @TestName = N'[TestSample].[test spDouble Calculation]'
.
If the test succeeds, you’ll see a message indicating that the test passed. If the test fails, you’ll be notified of the failure and the reason for it. This allows you to quickly identify and fix any issues in your code.
In conclusion, tSQLt is a powerful framework that makes unit testing T-SQL code in SQL Server a breeze. This article provided a quick introduction to getting started with tSQLt. There is much more to learn and explore with the framework, so be sure to check out the documentation and articles available on the tsqlt.org website. Happy testing!