Friday, 23 March 2012

tSQLt - Writing tests

I am not going to go into detail on how to download and install tSQLt here as it is pretty straight forward and all the instructions are on the tSQLt website. 
It's worth creating a test database in order to try out the examples in the code below.  Once you have created the test database follow the instructions on the tSQLt website to install tSQLt on this database.
Once tSQLt is installed the obvious starting point would be to write and run a test.


tSQLt introduces a concept of a TestClass.  This is a class that is used to group a set of unit tests. tSQLt uses schema's to accomplish this.  I am currently using the following naming convention UnitTests_<schemaName> where the schemaName is the name of the schema that contains the code that is being tested.
Creating a TestClass:

EXEC tSQLt.NewTestClass 'UnitTests_Processing'

Use this query to view your TestClasses:

SELECT * FROM tSQLt.TestClasses

And to delete a TestClass

EXEC tSQLt.DropClass 'UnitTests_Processing'
You actually don't need to create a TestClass as shown above.  You can just create a normal schema and start writing tests against that schema.  The downside of doing this is that the schema won't be correctly registered with tSQLt and commands like

EXEC tSQLt.RunAll
won't run these tests.

Writing a test is as simple as creating a stored procedure within a test schema (TestClass).  All test stored procedures need to start with the word "test". Test names can include spaces.

CREATE PROCEDURE [UnitTests_Processing].[test 1 should equal 1]
AS
BEGIN
-- this is the simplest example of an assert
    EXEC tSQLt.AssertEquals 1, 1, '1 should equal 1'
END

That is it for now.

No comments:

Post a Comment