首页 > 解决方案 > 如何避免 tSQLt 在 raiserror 之后中止调用的过程?

问题描述

在我们的存储过程中,我们喜欢在使用 raiserror() 引发和出错后“返回”一个特定的返回值

为此,我们使用低严重级别(例如 12),然后是返回值,例如:

create or alter proc dbo.usp_test 
as
begin
    print '**start of proc'
    raiserror( 'error on purpose',12,1);
    print '**after the error'
    return -3
end

这在运行该过程时完美运行:

declare @RC int
exec @RC = dbo.usp_test
print concat('The return code is ', @RC)

    /* output:

    **start of proc
    Msg 50000, Level 12, State 1, Procedure usp_test, Line 6 [Batch Start Line 12]
    error on purpose
    **after the error
    The return code is -3

    */

但是,当从单元测试中调用该 proc 时,行为是不同的,在 raiserror 之后突然停止执行:

create schema T_usp_test authorization dbo;
GO
EXECUTE sp_addextendedproperty @name = 'tSQLt.TestClass', @value = 1, @level0type = 'SCHEMA', @level0name = 'T_usp_test'

GO

create or alter proc T_usp_test.[test mytest]
as
begin

    exec tSQLt.ExpectException;

    declare @RC int;
    exec @RC = dbo.usp_test;
    print concat('The return code is ', @RC)


end

GO

exec tSQLt.Run 'T_usp_test.[test mytest]'

    /* output:


    (1 row affected)
    **start of proc

    +----------------------+
    |Test Execution Summary|
    +----------------------+

    |No|Test Case Name            |Dur(ms)|Result |
    +--+--------------------------+-------+-------+
    |1 |[T_usp_test].[test mytest]|      7|Success|
    -----------------------------------------------------------------------------
    Test Case Summary: 1 test case(s) executed, 1 succeeded, 0 failed, 0 errored.
    -----------------------------------------------------------------------------

    */

所以问题:

1)为什么行为不同,proc现在突然停止执行raiserror()

2)我怎样才能克服这个?

标签: tsqlt

解决方案


运行测试的核心过程是 tSQLt.Private_RunTest,它在 TRY...CATCH 块中运行测试。来自https://docs.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-2017的文档:

A TRY...CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection.

看起来您已将严重性设置为 12。考虑降低 RAISERROR 调用的严重性,看看是否会改变行为。您也可以尝试将您的 RAISERROR 调用包装在它自己的 TRY...CATCH 块中。


推荐阅读