30 Days of Automated Testing:Using PHPUnit【D09】
In the previous articles, we have practiced testing APIs and databases. Today, let’s take a break and introduce some Traits provided by Laravel that are related to automated testing.
DatabaseMigrations
After using this trait, will execute migrate
before each test is run and then migrate:rollback
after each test is executed, this will ensure that every test run has a fresh and empty database.
DatabaseTransactions
The above code, when this Trait is used, will start a database Transaction
before each test is run, and then roll back
the transaction after the test is executed, achieving a similar effect of resetting the database.
RefreshDatabase
It can be considered as a combination of DatabaseMigrations
and DatabaseTransactions
. When using it, it will determine whether the current test data is in-memory. If it is, it will execute the migration; if not, it will check before each test if migration has been executed, and if not, it will execute it and start the database Transaction
mechanism.
The main difference between DatabaseMigrations and RefreshDatabase is that DatabaseMigrations resets the auto-generated ID whereas RefreshDatabase does not.
WithoutMiddleware
The above code means that sometimes when we test a feature, it will pass through a Middleware
, and sometimes in order to make the test pass through the Middleware
, we may need to do some preparation, such as manually creating a Bearer Token and placing it in the header, in order to pass the Auth
middleware.
However, sometimes the logic of the Middleware
is not what we want to test, in this case, we can use this trait, allowing us to bypass the Middleware
layer during testing so that we can focus on the object and behavior we want to test.
WithoutEvents
Sometimes when we don’t want to trigger various events during the test execution, we can use this Triat. However, the author has not used it in practice.
WithFaker
This trait allows us to generate fake data values in our test code as we wish.
The above is an introduction to several Traits for automated testing that we covered today. It is recommended that you try implementing a few examples yourself. However, when it comes to Traits related to the database, if you are not familiar with them, it is suggested that you test with an empty database.
The next article, we will discuss testing for Auth.
If you liked this article or found it helpful, feel free to give it some claps and follow the author!
Reference
- https://mayahi.net/laravel/make-refresh-database-trait-much-faster/
- https://blog.goodjack.tw/2018/09/laravel-testing-with-faker.html
- https://laravel.com/docs/9.x/middleware
- https://laravel.com/docs/9.x/database-testing
- https://laravel.com/docs/9.x/migrations
- https://stackoverflow.com/questions/48510661/laravel-5-5-testing-with-databasemigrations-deletes-all-tables
- https://ithelp.ithome.com.tw/articles/10223852
- https://devs.tw/post/258