Eloquent Model Testing in Laravel

4:50 AM Unknown 1 Comments

In these days software testing is essential for the software development process, TDD, BDD etc are the popular methods of Software Testing. In TDD at first we write the test functions and then we will make functions which need to pass the tests. In These days i am learning about TDD in which some of the testing such as unit testing, integration testing, regression testing . I am weak in software testing  But Software testing is fun and interesting for me at this time. Using TDD it ensures my code is correct and reliable code that's why i need to use testing.

Today I am watching the video tutorials from Laracasts.com, I understand some testing jargon about the Eloquent Model Testing in Laravel In the following way.

First I downloaded the Laravel project and create database in phpmyadmin and  configure for the database  credentials in .env file of the laravel.

Now i Create a simple Article Model and migration file for articles table using the command php artisan make:model Article -m   

I am Just added just these columns for the articles table, Which is shown in the below figure.



And Just create the table using the commands php artisan migrate:install and php artisan migrate.
Now tables are created in the database.

Now create the factory method inside of the ModelFactory.php which will useful to add the records in the database tables. I am making the factory method for the articles table, which is shown follwing.




For the Model Test I create the  test class ArticleTest.php inside of the tests/integration/models folder and test class is as follows.

 

Now If i run the test using the phpunit  command then it Sure fails Because I do not created the trending() function in the Article.php Model. In above testing shows that At First two articles are created using the factory method, one article created with value of 10 in the reads column and another article is created with value of 20 in the reads column. After then trending() method is called and stored the result in $articles variable. Now actual comparing started using the assertEquals and assertCount methods which is quite simple. Ok How trending() method is organized in the Article.php is shown below.



Now Run the phpunit and my test will work. The Source code is available in github in this link https://github.com/madhusudhan1234/testing-lession

1 comment: