如何将索引应用于tSQLt中的伪表

时间:2014-07-16 17:21:07

标签: sql sql-server unit-testing tsqlt

对MS SQL Server(2012)使用优秀的tSQLt测试框架(v1.0.5137.39257),我正在尝试构建一个测试来检查UNIQUE INDEX是否有效并在复制时生成异常插入值。

经过大量搜索后,我找不到将索引应用于伪造的表(内置tSQLt proc或额外代码)的方法。需要tSQLt.ApplyIndex之类的东西。有没有人设法做到这一点?

另一种可能性是分叉tSQLt代码并根据http://gallery.technet.microsoft.com/scriptcenter/SQL-Server-Generate-Index-fa790441处的代码添加一个proc来重新创建伪造表上的索引。然而,这将是相当多的工作......

测试条件(假设数据库中已安装tSQLt):

-- Create a sample table with a UNIQUE INDEX
SET ANSI_NULLS, QUOTED_IDENTIFIER, ANSI_PADDING ON
GO
CREATE TABLE dbo.tblTestUniqueIndex (
  id INT NOT NULL IDENTITY (1, 1),  TheField varchar(50) NOT NULL,
  CONSTRAINT PK_tblTestUniqueIndex PRIMARY KEY CLUSTERED (id ASC)
) ON [PRIMARY];
GO
CREATE UNIQUE NONCLUSTERED INDEX UX_TestUniqueIndex ON dbo.tblTestUniqueIndex
(TheField ASC)
ON [PRIMARY];
GO

创建测试类,测试并运行它(当然它失败了,因为过程调用ApplyIndex不存在):

EXEC tSQLt.NewTestClass 'tests';
GO
CREATE PROCEDURE tests.[test that inserting a duplicate value in tblTestUniqueIndex raises an error]
AS
BEGIN
  EXEC tSQLt.FakeTable @TableName='dbo.tblTestUniqueIndex';

  -- WE NEED SOMETHING LIKE THIS
  --EXEC tSQLt.ApplyIndex @TableName='dbo.tblTestUniqueIndex', @ConstraintName='UX_TestUniqueIndex' 

  EXEC tSQLt.ExpectException;

  INSERT dbo.tblTestUniqueIndex (TheField) VALUES ('Cape Town');
  INSERT dbo.tblTestUniqueIndex (TheField) VALUES ('Cape Town');

END;
GO
EXEC tSQLt.Run 'tests.[test that inserting a duplicate value in tblTestUniqueIndex raises an error]'
GO

当然,如果没有索引工作,上述测试就会失败。

清理:

DROP PROCEDURE tests.[test that inserting a duplicate value in tblTestUniqueIndex raises an error]
GO
EXEC tSQLt.DropClass 'tests'
GO
DROP TABLE dbo.tblTestUniqueIndex
GO

由于

3 个答案:

答案 0 :(得分:4)

您是否可以不创建唯一约束?您仍然可以获得所需的索引。 tSQLt.ApplyConstraint适用于与主键相同的唯一键 - 但仅限于最新版本的IIRC。例如:

从您在上面创建的表的类似版本开始,为每种类型的唯一约束中的一种提供足够的列

-- Create a sample table with a UNIQUE INDEX
set ansi_nulls, quoted_identifier, ansi_padding on
go

if object_id('dbo.StackTable') is not null
    drop table dbo.StackTable;

create table dbo.StackTable
(
  Id int not null identity(1, 1)
, UniqueKeyColumn varchar(50) null
, UniqueIndexColumn int null
);
go

if object_id('PK_StackTable') is null
    alter table dbo.StackTable add constraint [PK_StackTable]
        primary key clustered (Id);
go

if object_id('AK_StackTable_UniqueKeyColumn') is null
    alter table dbo.StackTable add constraint [AK_StackTable_UniqueKeyColumn]
        unique nonclustered  (UniqueKeyColumn);
go

if object_id('NCI_StackTable_UniqueIndexColumn') is null
    create unique nonclustered index [NCI_StackTable_UniqueIndexColumn]
        on dbo.StackTable (UniqueIndexColumn);
go

创建一个新的测试类(假设已经安装了最新版本1.0.5325.27056)

if schema_id('StackTableTests') is null
    exec tSQLt.NewTestClass @ClassName = 'StackTableTests';
go

第一个测试确认Id被限制为唯一且约束是主键

if object_id('[StackTableTests].[test id is unique]') is not null
    drop procedure [StackTableTests].[test id is unique];
go

create procedure [StackTableTests].[test id is unique]
as
begin
    exec tSQLt.FakeTable @TableName = 'dbo.StackTable';
    exec tSQLt.ApplyConstraint @TableName = 'dbo.StackTable', @ConstraintName = 'PK_StackTable';

    --! Add the row we're going to duplicate
    insert dbo.StackTable (Id) values (-999);

    --! If we insert the same value again, we should expect to see an exception
    exec tSQLt.ExpectException @ExpectedErrorNumber = 2627
        , @ExpectedMessagePattern = 'Violation of PRIMARY KEY constraint%';

    insert dbo.StackTable (Id) values (-999);
end
go

下一个测试还使用ApplyConstraint确认UniqueKeyColumn也使用唯一约束约束为唯一

if object_id('[StackTableTests].[test UniqueKeyColumn is unique]') is not null
    drop procedure [StackTableTests].[test UniqueKeyColumn is unique];
go

create procedure [StackTableTests].[test UniqueKeyColumn is unique]
as
begin
    exec tSQLt.FakeTable @TableName = 'dbo.StackTable';
    exec tSQLt.ApplyConstraint
        @TableName = 'dbo.StackTable', @ConstraintName = 'AK_StackTable_UniqueKeyColumn';

    --! Add the row we're going to duplicate
    insert dbo.StackTable (UniqueKeyColumn) values ('Oops!');

    --! If we insert the same value again, we should expect to see an exception
    exec tSQLt.ExpectException @ExpectedErrorNumber = 2627
        , @ExpectedMessagePattern = 'Violation of UNIQUE KEY constraint%';

    insert dbo.StackTable (UniqueKeyColumn) values ('Oops!');
end
go

目前,测试唯一索引的唯一方法是反对真实的,未伪造的表。在此示例中,UniqueKeyColumnvarchar(50),因为这是真实表,它可能已包含数据。所以我们需要能够指定两个唯一值,以便我们的测试不会破坏错误的约束。最简单的方法是使用几个GUID。

if object_id('[StackTableTests].[test UniqueIndexColumn is unique]') is not null
    drop procedure [StackTableTests].[test UniqueIndexColumn is unique];
go

create procedure [StackTableTests].[test UniqueIndexColumn is unique]
as
begin
    --! Have to use the real table here as we can't use ApplyConstraint on a unique index
    declare @FirstUniqueString varchar(50) = cast(newid() as varchar(50));
    declare @NextUniqueString varchar(50) = cast(newid() as varchar(50));

    --! Add the row we're going to duplicate
    insert dbo.StackTable (UniqueKeyColumn, UniqueIndexColumn) values (@FirstUniqueString, -999);

    --! If we insert the same value again, we should expect to see an exception
    exec tSQLt.ExpectException @ExpectedErrorNumber = 2601
        , @ExpectedMessagePattern = 'Cannot insert duplicate key row in object ''dbo.StackTable'' with unique index%';

    insert dbo.StackTable (UniqueKeyColumn, UniqueIndexColumn) values (@NextUniqueString, -999);
end
go

exec tSQLt.Run '[StackTableTests]';
go

对真实表进行测试的潜在问题是它可能具有对其他表的外键引用,而这些表又可能具有对其他表的其他FK引用,依此类推。没有简单的方法可以解决这个问题,但我已经实现了Test Data Builder模式的一个版本。这背后的想法是每个实体的存储过程,它自动处理这些依赖关系(即向父和父父表添加任何必要的行)。通常,创建所有依赖项后,TDB sproc会将结果ID作为输出参数提供,以便可以重用这些值。

因此,如果我使用的是Test Data Builder模式,我的测试可能如下所示:

create procedure [StackTableTests].[test UniqueIndexColumn is unique]
as
begin
    --! Have to use the real table here as we can't use ApplyConstraint on a unique index
    declare @FirstUniqueString varchar(50) = cast(newid() as varchar(50));
    declare @NextUniqueString varchar(50) = cast(newid() as varchar(50));
    declare @NewId int;

    --! Add the row we're going to duplicate
    -- The TDB should output the ID's of any FK references so they
    --! can be reused on the next insert
    exec TestDataBuilders.StackTableBuilder
              @UniqueKeyColumn = @FirstUniqueString
            , @UniqueIndexColumn = -999

    --! If we insert the same value again, we should expect to see an exception
    exec tSQLt.ExpectException @ExpectedErrorNumber = 2601
        , @ExpectedMessagePattern = 'Cannot insert duplicate key row in object ''dbo.StackTable'' with unique index%';   

    insert dbo.StackTable (UniqueKeyColumn, UniqueIndexColumn) values (@NextUniqueString, -999);
end
go

exec tSQLt.Run '[StackTableTests]';
go

几年前,我写了一篇关于使用Test Data Builder pattern for SQL的博客文章。我希望这有助于解释我的想法。

答案 1 :(得分:0)

首先,我必须承认我喜欢你在你的例子中选择的城市。我不明白为什么你在这个例子中使用FakeTable。为什么不在没有FakeTable的情况下编写测试并对真实表进行测试。有些情况下这可能会有点痛苦。即如果你有一个包含许多必填字段的表,但实际上可能有更好的方法来编写你想要的测试。如果您通过插入重复行来检查唯一约束或主键,我建议您测试SQL Server本身的功能是否按预期工作。如果我要编写测试,我会通过查询information_schema或sys表来测试约束是否存在。

答案 2 :(得分:0)

CREATE TABLE TestTable (
        FirstName VARCHAR(255),
        LastName VARCHAR (255),
        Gender VARCHAR (255),
        Age INT
    );

INSERT INTO TestTable (FirstName, LastName, Gender, Age) VALUES ('Tapos','Noor','Female',21);

ALTER TABLE TestTable ADD CONSTRAINT My_Constraint UNIQUE (FirstName);

EXEC tSQLt.FakeTable @TableName = 'TestTable';
EXEC tSQLt.ApplyConstraint @TableName = 'TestTable', @ConstraintName = 'My_Constraint';

INSERT INTO TestTable (FirstName, LastName, Gender, Age) VALUES ('Tapos', 'Noor', 'Male',24);

EXEC tSQLt.ExpectException @ExpectedErrorNumber = 2627
        , @ExpectedMessagePattern = 'Violation of UNIQUE KEY constraint%';

INSERT INTO TestTable (FirstName, LastName, Gender, Age) VALUES ('Narullah', 'Noor', 'Male',24);