使用tSQLt测试唯一的过滤索引

时间:2017-08-04 08:59:17

标签: sql-server unit-testing tsqlt

目前我正在尝试测试具有唯一过滤索引的表。到目前为止我发现的唯一建议是使用CONSTRAINT而不是索引,因为tSQLtApplyConstraint SP。但是我无论如何都找不到如何做过滤约束...有什么建议吗?

CREATE TABLE [dbo].[prime_rates]
(
    [prime_rate] DECIMAL(5, 3) NOT NULL
  , [start_date] DATE          NOT NULL
  , [end_date]   DATE          NOT NULL
        DEFAULT '12/31/2099'
);
GO

CREATE UNIQUE INDEX [UIX_prime_rates_end_date]
    ON [dbo].[prime_rates] ([end_date])
    WHERE [end_date] = '12/31/2099';
GO

CREATE PROCEDURE [Test Class1].[test when 2 active prime rates are inserted then raise error]
AS
    BEGIN

        EXEC tSQLt.FakeTable @TableName = N'prime_rates';

        EXEC tSQLt.ApplyConstraint 'dbo.prime_rates', 'UIX_prime_rates_end_date';

        INSERT INTO dbo.prime_rates (   prime_rate
                                      , start_date
                                      , end_date
                                    )
        VALUES (   1            -- prime_rate - decimal(5, 3)
                 , GETDATE()    -- start_date - date
                 , '2099-12-31' -- end_date - date
               );

        EXEC tSQLt.ExpectException @ExpectedSeverity = 16;

        INSERT INTO dbo.prime_rates (   prime_rate
                                      , start_date
                                      , end_date
                                    )
        VALUES (   1            -- prime_rate - decimal(5, 3)
                 , GETDATE()    -- start_date - date
                 , '2099-12-31' -- end_date - date
               );
    END;

1 个答案:

答案 0 :(得分:2)

基本上,您正在测试没有意外的架构更改已经破坏(删除/禁用/更改了谓词)您的唯一过滤索引。

如果您伪造了表格,那么您需要将自己的唯一过滤索引添加到伪造的内容中,从而否定了这一点。

这应该有用。

CREATE PROCEDURE [Test Class1].[test when 2 active prime rates are inserted then raise error]
AS
  BEGIN
      IF @@TRANCOUNT = 0
        THROW 50000, 'This must be run in a transaction and rolled back afterwards. Use "EXEC tSQLt.RunAll;" etc. Don''t run directly ', 1;


      TRUNCATE TABLE dbo.prime_rates;

      INSERT INTO dbo.prime_rates
                  (prime_rate,
                   start_date,
                   end_date)
      VALUES      ( 1 -- prime_rate - decimal(5, 3)
                    ,GETDATE() -- start_date - date
                    ,'2099-12-31' -- end_date - date
      );

      EXEC tSQLt.ExpectException @ExpectedSeverity = 16;

      INSERT INTO dbo.prime_rates
                  (prime_rate,
                   start_date,
                   end_date)
      VALUES      ( 1 -- prime_rate - decimal(5, 3)
                    ,GETDATE() -- start_date - date
                    ,'2099-12-31' -- end_date - date
      );
  END