简体   繁体   English

在更新以测试Spring事务管理时如何模拟异常?

[英]How to simulate an exception while updating to test the spring transaction management?

I have under the same spring managed transaction an array of updates as below: 在同一个春季托管事务下,我有一系列更新,如下所示:

someRepositoryA.updateEntityA(...)
someRepositoryB.updateEntityB(...)
someRepositoryC.updateEntityC(...)

How can I simulate that someRepositoryB.updateEntityB(...) throws an Exception ? 我如何模拟someRepositoryB.updateEntityB(...)引发Exception That will allow me to see that the changes made by A were revoked. 这将使我看到A所做的更改已被撤消。 Since I will test the transaction I cannot mock the repository, but I will use some in-memory database. 由于我将测试事务,因此无法模拟存储库,但将使用一些内存数据库。

I wouldn't simulate an exception, I'd make something genuinely go wrong. 我不会模拟异常,我会确实出错。

You're using an in-memory database so you have control of your test data. 您正在使用内存数据库,因此可以控制测试数据。 Also it's a better test (less chance of bad assumptions invalidating your results) if you're recreating a real problem instead of faking out something. 如果您要创建一个真正的问题而不是弄虚作假,那么它也是一个更好的测试(错误假设使您的结果无效的可能性较小)。

The easiest way to test your transaction would be to have the test create a B with data chosen so that the update will cause a referential integrity constraint to be violated (Do you have any not-null constraints? Otherwise you can introduce an invalid primary key value, by re-using an existing value). 测试事务的最简单方法是让测试创建一个选择了数据的B,这样更新将导致违反参照完整性约束(您是否有任何非空约束?否则,您可以引入无效的主键值(通过重用现有值)。 The RI violation will cause an exception to get thrown. 违反RI将导致引发异常。

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

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