簡體   English   中英

如何在StoredProcedure中模擬/偽造RaiseError

[英]How do I mock/fake a RaiseError with in a StoredProcedure

這是我使用tsqlt第一天,所以你可以期待一些模糊的陳述。

我正在嘗試測試一個帶有Try Catch Block的storedProcedure,但測試中的實際語句是insert和update命令。

現在我想測試是否存在ErrorRaised我的catch塊是否執行預期的任務。

你能否指導我如何從測試中的存儲過程中提出錯誤,我們沒有任何內容模擬/偽造。

希望我的問題是可以理解的,如果需要,我很樂意澄清。

因此,如果我正確理解您的問題,您是否正在嘗試測試您的catch塊是否有效?

執行此操作的方法取決於catch塊中發生的情況。 想象一下這種情況:

create table mySimpleTable
(
  Id int not null primary key
, StringVar varchar(8) null 
, IntVar tinyint null
)
go

我們有一個存儲過程,可以將數據插入此表中。

這基於我在許多程序中使用的模板。 它首先驗證輸入,然后完成它需要做的工作。 命名每個步驟對於了解更復雜的多步驟過程中錯誤發生的位置特別有用。 catch塊使用我的Log4TSql日志框架,您可以在我的博客上閱讀更多信息並從SourceForge下載。

我遵循的模式是捕獲有關異常的信息以及catch塊中錯誤發生時過程正在執行的操作,但確保在過程結束時仍然拋出錯誤。 您也可以選擇在catch塊中調用raiserror(也throw 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

讓我們首先創建一個新的模式(類)來保存我們的測試。

exec tSQLt.NewTestClass 'mySimpleTableInsertTests' ;
go

我們的第一個測試是最簡單和最簡單的檢查,即使我們的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

我們的第二個測試稍微復雜一點,並使用tsqlt.SpyProcedure “模擬”ExceptionHandler,否則會記錄異常。 在引擎蓋下,當我們以這種方式模擬一個過程時,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

最后,如果@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

如果這不能回答你的問題,也許你可以發布一個你想要實現的例子。

您在SQL Server中使用RAISERROR來實現此目的:

RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );

您可以在MSDN網站上查看更多信息: RAISERROR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM