Search code examples
sqlsql-serverunit-testingssmstsqlt

tSQLt How can I tell if a table has been faked


I am just starting creating some unit tests for my database.

If I have faked a table,

EXEC tSQLt.FakeTable
    @TableName = 'dbo.[My Table]',
    @Identity = 0,
    @ComputedColumns = 0,
    @Defaults = 0

Can I check if it has been faked?

Note that documentation on the FakeTable SP can be found here.

Motivation

I want to be able to do this as I imagine creating several stored procedures which populate these faked tables so I can perform tests. However I do not want to handle faking the tables in the stored procedures (so I can call them multiple times entering different info each time).

I don't want to have the possibility that I forget to fake the table before adding the data (as would almost certainly cause me to fail my test).


Solution

  • tSQLt adds an extended property to a fake table to track the table it fakes. This is easily tested using the function tSQLt.Private_GetOriginalTableName:

    SELECT tSQLt.Private_GetOriginalTableName('dbo','[My Table]')
    

    This will return NULL if the table isn't faked.

    If you want to do something more complex, you can query sys.extended_properties directly. See the contents of the tSQLt.class.sql script (in the tSQLt distribution) for the definition of tSQLt.Private_GetOriginalTableName.