英文:
How to rollback all database changes after all tests finished in Laravel 9
问题
我正在尝试找到一种方法,在我的测试完成后一次性回滚所有数据库(mysql)更改(事务)。不是在每个测试方法之后,而是在所有测试完成后。我读到DatabaseTransactions
特性用于这种方法,但它在每个测试方法之后回滚数据库事务。操作如下:
运行Test1 -> 执行数据库事务 -> 回滚 -> 运行Test2 ..... -> 运行LastTest -> 回滚
附注:我知道我应该为测试使用不同的数据库,并可以使用RefreshDatabase
特性。但在我的情况下,我不能使用不同的数据库。请不要问为什么)
英文:
I am trying to find a way to rollback all database (mysql) changes (transactions) once after my tests finished. Not after each test method but after all of them done. I read that DatabaseTransactions
trait is used for this kind of approach but it rolls db transactions back after each test method. Operation going like:
Run Test1 -> Perform DB transactions -> Rollback -> Run Test2 ... -> Run LastTest
But what I need:
Run Test1 -> Perform DB transactions -> Run Test2 ..... -> Run LastTest -> Rollback
PS: I know I should use different database for testing and can use RefreshDatabase
trait for it. But in my case I can't use different database. Please don't ask why)
答案1
得分: 1
对于未来可能会感到困惑的任何人,我强烈建议在单元测试中使用模拟来伪造数据库和第三方API。经过进一步的研究,我发现单元测试应该彼此独立。它们不应影响数据库,并且在测试时不应调用第三方API。
要了解更多关于Laravel中的“模拟”,请查看以下链接:
https://laravel.com/docs/9.x/mocking
https://ralphjsmit.com/laravel-mock-dependencies
https://matthewdaly.co.uk/blog/2018/02/25/unit-testing-your-laravel-controllers
英文:
For anyone who might get confused like me in the future I highly recommend to use Mocking for Unit testing to fake both your database and 3rd party APIs. After making some more research I have found that Unit tests should be independent from each other. They shouldn't affect database and 3rd party APIs shouldn't got called while testing.
For more understanding mocking
in laravel please check out the links:
https://laravel.com/docs/9.x/mocking
https://ralphjsmit.com/laravel-mock-dependencies
https://matthewdaly.co.uk/blog/2018/02/25/unit-testing-your-laravel-controllers
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论