0

I've just gotten started with unit testing (I'm reading Laravel Testing Decoded by Jeffrey Way). I'm not sure how to test the "exists" validation rule in isolation since it queries the database. I think maybe I need to mock the database query somehow? If so, I'm not sure how to do that.

To be clear, I want to test that business rules are being enforced, not to test that the validator is working correctly. Also, I'm doing validation in the model with Ardent so it's the model that is being testing.

As an example, the "required" rule is straightforward to test. You fill every field with valid data, except for the one you are testing which is left null. Then you assert that validation failed. (The book has examples of this) But testing "exists" or "unique" needs to touch the database.

4

1 回答 1

4

简短的回答:

不。

您尝试创建的测试已经通过 Laravel 的核心测试套件进行了测试。

更长的答案:

如果您想测试您的特定规则是否适用于您的数据集,那么您需要进行与您的数据交互的单元测试!

Laravel 附带的基础TestCase足以引导应用程序,以便您可以执行此操作。

也许使用种子 sqllite 内存数据库而不是您的真实数据库进行单元测试。

否则,您可以放心地假设验证库已经过全面测试并且可以运行- 无需重新测试。已经有测试以确保“存在”按应有的方式工作。剩下的唯一因素是您的数据是否支持测试。

最后:

测试时,请注意您的单元测试有多么有用。您不一定需要 100% 的代码覆盖率。您尤其不一定需要测试框架覆盖范围已经测试过的内容。如果您想知道什么是好的单元测试(以及单元测试与集成测试之间的区别),请查看这篇关于编写好的测试的优秀文章

希望这可以帮助!

于 2013-10-08T12:44:45.997 回答