简体   繁体   English

使用 TSQLUNIT 进行 SQL 单元测试

[英]SQL Unit Testing with TSQLUNIT

I noticed something weird while unit testing an update/insert stored procedure using TSQLUNIT on SQL Server 2012. when I call Exec tsu_RunTests , my test procedure runs but with unexpected behaviour.在 SQL Server 2012 上使用 TSQLUNIT 对更新/插入存储过程进行单元测试时,我注意到了一些奇怪的事情。当我调用Exec tsu_RunTests 时,我的测试过程运行但出现意外行为。 the line in the code that calls my original stored procedure is executed but no actual updates or inserts made to the database table as expected.代码中调用我的原始存储过程的行被执行,但没有按预期对数据库表进行实际更新或插入。 Is there a valid reason for this behaviour?这种行为是否有正当理由? Or is this a bug I need to pay much attention to?或者这是一个我需要非常注意的错误? I notice that when I execute the same original stored procedure outside of the test procedure, it works fine.我注意到当我在测试过程之外执行相同的原始存储过程时,它工作正常。

You can use Default parameter for each stored procedure and set this @IsTest parameter to true when use these stored procedures in tsu_RunTests.您可以为每个存储过程使用默认参数,并在 tsu_RunTests 中使用这些存储过程时将此@IsTest参数设置为 true。

CREATE PROCEDURE orginal_proc
    --@parameter_name 
    @IsTest BIT = 0
AS
    if @IsTest <> 1 Begin
    --  Test statements
    End Else Begin
    --  statements
    End 
GO

you also can use @@NESTLEVEL for check that your procedure execute directly or execute by other procedure.您也可以使用@@NESTLEVEL来检查您的程序是直接执行还是由其他程序执行。

CREATE PROCEDURE orginal_proc
    --@parameter_name 
AS

    if @@NESTLEVEL <> 1 Begin
    --  Test statements
    End Else Begin
    --  statements
    End
GO

EDIT : Stored Procedure Code must be like below :编辑:存储过程代码必须如下所示:

If @@NESTLEVEL <> 1 Print 'Befor Update Message'
If @@NESTLEVEL = 1 Begin
   Update YourTable
   Set ...
End
If @@NESTLEVEL <> 1 Print 'After Update Message'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM