Hey everyone!
Here are some tips that might help you test your applications. I had it previously posted as a twitter thread. Sadly I could not inline images here so it might be useful to look at the thread.
- Don't be afraid to hit the database. Today DB calls are very fast, and if you're mocking the database you're usually not testing the feature completely. It makes sense to write "pure" unit tests on lower-level things like libraries, though.
- Reverse test when testing code that already exists. A easy way to make sure your new tests cover an existing feature is to comment out blocks of code (specially if blocks) and see if the tests break. If they don't, you're missing something.
- It's better to write some "unnecessary " tests than not to write them, so If you're wondering wether a test will be useful, just write it. Those few minutes might help you a lot later.
- Use fakes instead of mocking external services when possible. Laravel ships with many fakes, and when you need a custom one it's easy to swap the implementation for a fake on the container. That's possible on anything that has a container. The tweet ocntains an example using Laravel's Facades.
- Tests are important, but don't let them hold you back. If you feel thinking how the API is going to look before writing the code is holding you back, just forget the tests for a moment. You can come back later and write them. Writing them before is not a exactly a rule.
Top comments (5)
The best way to "Mock a database" is to create a SQLite database on the fly inside your unit tests and test against that. That way whatever code you're using to fetch and post data can be tested against that, should you not want to hit your database directly. As for hitting the real database, this should be part of a larger "Integration Test", where you start all the way at the front end by making a web request and ensuring that your data is fetched/posted properly at the database.
But just remember sometimes if you use an special DB function SQLite won’t be enough.
Great point Oziel
Love these! 🙌