如何在StoredProcedure中模拟/伪造RaiseError

Mud*_*uds 5 sql unit-testing tsqlt tsqlunit

这是我的第一天,tsqlt所以你可以期待一些模糊的陈述.

我试图测试一个storedProcedure,它有一个Try Catch Block但是测试中的实际语句是insert和update命令.

现在我想测试是否存在ErrorRaised我的catch块是否执行预期的任务.

你能否指导我如何从测试中的存储过程中提出错误,我们没有任何内容模拟/伪造.

希望我的问题是可以理解的,如果需要,我很乐意澄清.

dat*_*ity 3

所以,如果我正确理解你的问题,你正在尝试测试你的 catch 块是否有效?

执行此操作的方法取决于 catch 块中发生的情况。想象一下这个场景:

create table mySimpleTable
(
  Id int not null primary key
, StringVar varchar(8) null 
, IntVar tinyint null
)
go
Run Code Online (Sandbox Code Playgroud)

我们有一个存储过程,可以将数据插入到该表中。

这是基于我在许多程序中使用的模板。它首先验证输入,然后执行需要执行的工作。为每个步骤命名对于了解更复杂的多步骤过程中错误发生的位置特别有用。catch 块使用我的 Log4TSql 日志记录框架,您可以在我的博客上阅读更多相关信息并从SourceForge下载。

我遵循的模式是捕获有关异常的信息以及在 catch 块中发生错误时过程正在执行的操作,但确保在过程结束时仍会引发错误。throw您还可以选择在 catch 块中调用 raiserror(也在SQL2012 上)。不管怎样,我相信如果一个过程遇到异常,它应该总是被通知到链上(即从不隐藏)。

create procedure mySimpleTableInsert
(
  @Id int
, @StringVar varchar(16) = null
, @IntVar int = null
)
as
begin
    --! Standard/ExceptionHandler variables
    declare @_FunctionName nvarchar(255) = quotename(object_schema_name(@@procid))
             + '.' + quotename(object_name(@@procid));
    declare @_Error int = 0;
    declare @_ReturnValue int;
    declare @_RowCount int = 0;
    declare @_Step varchar(128);
    declare @_Message nvarchar(1000);
    declare @_ErrorContext nvarchar(512);

    begin try
        set @_Step = 'Validate Inputs'
        if @Id is null raiserror('@Id is invalid: %i', 16, 1, @Id);

        set @_Step = 'Add Row'
        insert dbo.mySimpleTable (Id, StringVar, IntVar)
        values (@Id, @StringVar, @IntVar)
    end try
    begin catch
        set @_ErrorContext = 'Failed to add row to mySimpleTable at step: '
                 + coalesce('[' + @_Step + ']', 'NULL')

        exec log4.ExceptionHandler
                  @ErrorContext   = @_ErrorContext
                , @ErrorProcedure = @_FunctionName
                , @ErrorNumber    = @_Error out
                , @ReturnMessage  = @_Message out
        ;
    end catch

    --! Finally, throw any exception that will be detected by the caller
    if @_Error > 0 raiserror(@_Message, 16, 99);

    set nocount off;

    --! Return the value of @@ERROR (which will be zero on success)
    return (@_Error);
end
go
Run Code Online (Sandbox Code Playgroud)

让我们首先创建一个新的模式(类)来保存我们的测试。

exec tSQLt.NewTestClass 'mySimpleTableInsertTests' ;
go
Run Code Online (Sandbox Code Playgroud)

我们的第一个测试是最简单的,只是检查即使我们的 catch 块捕获了异常,过程仍然返回错误。在此测试中,我们仅用于exec tSQLt.ExpectException检查当 @Id 提供为 NULL 时是否会引发错误(这会导致我们的输入验证检查失败)

create procedure [mySimpleTableInsertTests].[test throws error from catch block]
as
begin
    exec tSQLt.ExpectException @ExpectedErrorNumber = 50000;

    --! Act
    exec dbo.mySimpleTableInsert @Id = null
end;
go
Run Code Online (Sandbox Code Playgroud)

我们的第二个测试稍微复杂一些,它利用tsqlt.SpyProcedure“模拟”异常处理程序来记录异常。在幕后,当我们以这种方式模拟过程时,tSQLt 会创建一个以被监视的过程命名的表,并将所监视的过程替换为仅将输入参数值写入该表的过程。这一切都会在测试结束时回滚。这使我们可以检查 ExceptionHandler 是否被调用以及传递给其中的值。在此测试中,我们检查 mySimpleTableInsert 是否因输入验证错误而调用 ExceptionHander。

create procedure [mySimpleTableInsertTests].[test calls ExceptionHandler on error]
as
begin
    --! Set the Error returned by ExceptionHandler to zero so the sproc under test doesn't throw the error
    exec tsqlt.SpyProcedure 'log4.ExceptionHandler', 'set @ErrorNumber = 0;';

    select
          cast('Failed to add row to mySimpleTable at step: [Validate inputs]' as varchar(max)) as [ErrorContext]
        , '[dbo].[mySimpleTableInsert]' as [ErrorProcedure]
    into
        #expected

    --! Act
    exec dbo.mySimpleTableInsert @Id = null

    --! Assert
    select
          ErrorContext
        , ErrorProcedure
    into
        #actual
    from
        log4.ExceptionHandler_SpyProcedureLog;

    --! Assert
    exec tSQLt.AssertEqualsTable '#expected', '#actual';
end;
go
Run Code Online (Sandbox Code Playgroud)

最后,以下(有些人为的)示例使用相同的模式来检查是否捕获并抛出错误(如果 @IntVar 的值对于表来说太大):

create procedure [mySimpleTableInsertTests].[test calls ExceptionHandler on invalid IntVar input]
as
begin
    --! Set the Error returned by ExceptionHandler to zero so the sproc under test doesn't throw the error
    exec tsqlt.SpyProcedure 'log4.ExceptionHandler', 'set @ErrorNumber = 0;';

    select
          cast('Failed to add row to mySimpleTable at step: [Add Row]' as varchar(max)) as [ErrorContext]
        , '[dbo].[mySimpleTableInsert]' as [ErrorProcedure]
    into
        #expected

    --! Act
    exec dbo.mySimpleTableInsert @Id = 1, @IntVar = 500

    --! Assert
    select
          ErrorContext
        , ErrorProcedure
    into
        #actual
    from
        log4.ExceptionHandler_SpyProcedureLog;

    --! Assert
    exec tSQLt.AssertEqualsTable '#expected', '#actual';
end;
go
create procedure [mySimpleTableInsertTests].[test throws error on invalid IntVar input]
as
begin
    exec tSQLt.ExpectException @ExpectedErrorNumber = 50000;

    --! Act
    exec dbo.mySimpleTableInsert @Id = 1, @IntVar = 500
end;
go
Run Code Online (Sandbox Code Playgroud)

如果这不能回答您的问题,也许您可​​以发布一个您想要实现的目标的示例。