使用tSQLt测试时如何回滚事务 [英] How to ROLLBACK a transaction when testing using tSQLt

查看:188
本文介绍了使用tSQLt测试时如何回滚事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在调用一个在代码中包含rasierror的过程.抬高筹码的人正处于试捕区.同样,BEGIN TRAN在加注程序之后位于同一尝试捕获块中.如果事务中发生错误,则Catch块旨在回滚事务.这样做的方法是检查@@ TRANCOUNT是否大于0我知道它已经开始了事务并且需要ROLLBACK.使用tSQLt进行测试时,@@ TRANCOUNT始终> 0,因此,如果它碰到了CATCH块,则将执行ROLLBACK并且tSQLt失败(因为tSQLt在事务中运行).当我发现一个错误并且CATCH块运行时,tSQLt始终会通过测试.我没有办法测试是否正确处理raiserror.您将如何创建一个可能会回滚事务的测试用例?

I recently was calling a procedure that contained a rasierror in the code. The raiserror was in a try catch block. Also a BEGIN TRAN was in the same try catch block after the raiserror. The Catch block is designed to ROLLBACK the transaction if the error occurred in the transaction. The way it does this is to check the @@TRANCOUNT if it is greater that 0 I know that it had started a transaction and needs to ROLLBACK. When testing with tSQLt the @@TRANCOUNT is always >0 so if it ever hits the CATCH Block the ROLLBACK is executed and tSQLt fails (because tSQLt is running in a transaction). When I rasie an error and the CATCH block is run tSQLt always fails the test. I have no way to test for the correct handling of the raiserror. How would you create a test case that can potentially ROLLBACK a transaction?

推荐答案

如前所述,tSQLt在其自己的事务中运行每个测试.要跟踪正在发生的事情,需要依靠相同的事务在测试完成时仍处于打开状态. SQL Server不支持嵌套事务,因此您的过程将回滚所有内容,包括为当前测试存储的框架的状态信息.到那时,tSQLt只能假设确实发生了一些不好的事情.因此,它将测试标记为错误.

As you mentioned, tSQLt runs every test in its own transaction. To keep track of what is going on is relies on that same transaction to be still open when the test finishes. SQL Server does not support nested transactions, so your procedure rolls back everything, including the status information the framework stored for the current test. At that point tSQLt can only assume that something really bad happened. It therefore marks the test as errored.

如果在打开的事务中调用了该过程,SQL Server本身会抛出一个错误,从而阻止了过程内部的回滚.有关如何处理这种情况的方法以及其他信息,请查看我的博客文章有关如何回滚的内容程序.

SQL Server itself discourages a rollback inside a procedure, by throwing an error if that procedure was called within an open transaction. For ways to deal with this situation and some additional info check out my blog post about how to rollback in procedures.

这篇关于使用tSQLt测试时如何回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆