如何在 StoredProcedure 中 mock/fake 引发 RaiseError
How do I mock/fake a RaiseError with in a StoredProcedure
这是我与 tsqlt
的第一天,所以您可能会听到一些模糊的陈述。
我正在尝试测试具有 Try Catch Block
的存储过程,但测试中的实际语句是插入和更新命令。
现在我想测试如果出现 ErrorRaised,我的 catch 块是否执行预期的任务。
能否请您指导我如何从测试中的存储过程中引发错误,其中 mock/fake 里面没有任何内容。
希望我的问题是可以理解的,如果需要我很乐意澄清。
您在 SQL 服务器中使用 RAISERROR 来实现:
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
您可以在 MSDN 网站上查看更多信息:RAISERROR
所以如果我正确理解你的问题,你是在尝试测试你的 catch 块是否有效?
执行此操作的方法取决于您的 catch 块中发生的情况。想象一下这个场景:
create table mySimpleTable
(
Id int not null primary key
, StringVar varchar(8) null
, IntVar tinyint null
)
go
我们有一个存储过程可以将数据插入到这个 table 中。
这是基于我在许多程序中使用的模板。它从验证输入开始,然后做它需要做的工作。为每个步骤命名对于理解在更复杂的多步骤过程中发生错误的位置特别有用。 catch 块使用我的 Log4TSql 日志记录框架,您可以阅读有关 on my blog and download from SourceForge.
的更多信息
我遵循的模式是捕获有关异常的信息以及在 catch 块中发生错误时过程正在执行的操作,但确保在过程结束时仍会抛出错误。您还可以选择在 catch 块中调用 raiserror(在 SQL2012 上也是 throw
)。无论哪种方式,我相信如果一个过程遇到异常,它应该总是被通知到链上(即从不隐藏)。
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
让我们从创建一个新架构 (class) 开始我们的测试。
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
到 "mock" 否则会记录异常的 ExceptionHandler。在幕后,当我们以这种方式模拟一个过程时,tSQLt 创建一个以被侦测过程命名的 table,并将被侦测过程替换为仅将输入参数值写入 table 的过程。这一切都在测试结束时回滚。这使我们能够检查是否调用了 ExceptionHandler 以及传递给它的值。在此测试中,我们检查 ExceptionHander 是否由于输入验证错误而被 mySimpleTableInsert 调用。
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 的值对于 table:
来说太大,以下(有些人为的)示例使用相同的模式来检查是否捕获并抛出错误
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
如果这不能回答您的问题,也许您可以 post 举例说明您要实现的目标。
这是我与 tsqlt
的第一天,所以您可能会听到一些模糊的陈述。
我正在尝试测试具有 Try Catch Block
的存储过程,但测试中的实际语句是插入和更新命令。
现在我想测试如果出现 ErrorRaised,我的 catch 块是否执行预期的任务。
能否请您指导我如何从测试中的存储过程中引发错误,其中 mock/fake 里面没有任何内容。
希望我的问题是可以理解的,如果需要我很乐意澄清。
您在 SQL 服务器中使用 RAISERROR 来实现:
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
您可以在 MSDN 网站上查看更多信息:RAISERROR
所以如果我正确理解你的问题,你是在尝试测试你的 catch 块是否有效?
执行此操作的方法取决于您的 catch 块中发生的情况。想象一下这个场景:
create table mySimpleTable
(
Id int not null primary key
, StringVar varchar(8) null
, IntVar tinyint null
)
go
我们有一个存储过程可以将数据插入到这个 table 中。
这是基于我在许多程序中使用的模板。它从验证输入开始,然后做它需要做的工作。为每个步骤命名对于理解在更复杂的多步骤过程中发生错误的位置特别有用。 catch 块使用我的 Log4TSql 日志记录框架,您可以阅读有关 on my blog and download from SourceForge.
的更多信息我遵循的模式是捕获有关异常的信息以及在 catch 块中发生错误时过程正在执行的操作,但确保在过程结束时仍会抛出错误。您还可以选择在 catch 块中调用 raiserror(在 SQL2012 上也是 throw
)。无论哪种方式,我相信如果一个过程遇到异常,它应该总是被通知到链上(即从不隐藏)。
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
让我们从创建一个新架构 (class) 开始我们的测试。
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
到 "mock" 否则会记录异常的 ExceptionHandler。在幕后,当我们以这种方式模拟一个过程时,tSQLt 创建一个以被侦测过程命名的 table,并将被侦测过程替换为仅将输入参数值写入 table 的过程。这一切都在测试结束时回滚。这使我们能够检查是否调用了 ExceptionHandler 以及传递给它的值。在此测试中,我们检查 ExceptionHander 是否由于输入验证错误而被 mySimpleTableInsert 调用。
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 的值对于 table:
来说太大,以下(有些人为的)示例使用相同的模式来检查是否捕获并抛出错误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
如果这不能回答您的问题,也许您可以 post 举例说明您要实现的目标。