Testing in Laravel | How to Write Tests With Laravel | Laravel 8 Testing Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up developers this is dari here and welcome back to a new video where we're going to dive into a pretty important subject in laravel which is testing i recently started using my github more and more and i was thinking about adding a repository for every video with a usage section at the bottom which will basically show you how the code works in text if you are interested in this let me know in the comments section down below so i can continue on creating content like this as well also don't forget to give me a follow on github whether you are currently a developer or you're working in a different field we both can agree that testing is a good thing and that obviously applies for coding as well testing your code is a good thing and you are in fact supposed to do it there are some pretty good tools out there that you can use for testing think about php unit mockery php spec story play and way more but honestly it can be a lot to process when you start using it as a beginner instead of setting up your testing environment manually larval has php unit integrated in all projects you create php unit is a framework independent library that you can use for unit testing and unit testing is a method that you can use where small pieces of code will be tested against expected results you might wonder how and when you'll be using php units and think about situations like crawling your site's url or submitting forms or checking status codes up until this point you might have heard some terms that you might not have heard before so let's go over some of the most basic terms that you'll find in this video and whenever you search it on google as well the first term is actually the one that i just mentioned which is called unit testing unit testing will verify that individual units of code works as expected you can automatically generate unit tests but i prefer to write my own there's another type of testing which is feature testing where you will test the way individual units work together and you pass a message today's video is brought to you by cloudways a managed hosting platform for your applications pathways has enabled businesses to scale and reach new milestones instead of worrying about server hassles with reliable 24 7 support cloudways offers complete peace of mind from surfer level nightmares furthermore its superior tools and works enhance your productivity so you can focus on creating incredible experiences with your applications it's a fast managed solution for agencies smbs and e-commerce businesses what i personally like about clyde ways is their slogan moving dreams forward we've got regression tests where you're going to describe exactly what the user should be able to do and make sure that the application won't stop we've got http test which allows you to make simple http requests so get post put patch and delete we've got authentication responses where the application will be tested in authentication and authorization and we got database tests which are tools and assertions to make it easier to test database driven applications i think it's time to dive into the code and go over some of the basic stuffs that larval adds by default you don't need to configure anything for your testing environment which makes the process a lot easier as you can see i've already created a larval project and in the root of any larval project you can find a folder called tests if you have watched my previous larval videos you know that we actually never touched on the test folder if we open it now let me make my sidebar a little bit bigger you'll see two subfolders called feature and units and two php files which is the create application and the testcase.php file the features subfolder consist of tests that will cover the interaction between multiple units and in the unit subfolder you'll find tests for one unit of your code if we open both subfolders you'll see that both of them have an example.test file inside of it which has a let's see simple test example method inside of it which you can run if we open the creates application file you'll see that this file actually isn't a class but it is a trait and if we then open the test case you'll see that this trait of creates application is being used right here if we then open one of our example tests you can see that test case is being extended so the trait of creates application as well now if we take a look at the method that we have by default right here the test example you'll see that there isn't a lot of code which is actually a good thing because you need to keep your test method small inside the test underscore example method you can see a new object called response which is equal to this get forward slash uri then the response will check if the asset status is equal to 200 which is true because the forward flash is a route that has been defined by default let's test it out let's open the routes folder web.php and right here you can see that the forward slash endpoint does exist obviously one of the most important things is running your test luckily larval makes it very easy for us to run our tests through the terminal let's open the integrated terminal of visual studio code and let me make it a little bit bigger alright keep in mind that there are two different commands to run your test the first one is to run the php unit inside the vendor directory so inside the larval test folder over cli we need to run dot forward slash vendor for slash bin for slash php unit if we hit enter you'll see an output which might look a little bit weird for you so let's go over everything we're seeing right now first you can see that php unit is using version 9.5.9 and it has been created by sebastian bergmann and it's open source so contributors have added stuff in it as well then you'll see two dots right here which might not seem important to you but it actually indicates that we try to perform two tests we both have passed as you can see right here we have a score of one hundred percent so where are these two dots coming from like i said we have two example test files who have both been runs and now we open the unit folder as well right here you can see that it's checking if the assert true and we're passing in a true which is always equal to true now the second method that you can use in order to run your test is the php artisan test command so let's perform it let's say php artisan test hit enter and as you can see it has been outputted a little bit different than the previous command but i actually do like this method quite a lot i find it a very clear structured overview of your past test so you'll see the units folder right here which is an example method we have a examples test inside the features folder who also has an example file honestly it really doesn't matter which method you'll be using because you'll end up with the same exact result now the command that we just performed comes from the php unit file inside the root of our directory let's open it let's search for it first it's right here let me make it a little bit smaller again all right right here you'll find a place where you can configure specific options for your test there is actually quite a lot of code right here but the most important piece of code is the test suites right here this will basically make sure that php unit is able to run tests from the right here dot forward slash test for slash units folder and the features folder now the output that we had in the terminal is whenever your test passed the test let me show you what will happen if it doesn't pass the test the best possible way is to create a new test which can obviously be done through the terminal what we need to do is to run php artisan make colon test followed with a test name so let's call it user test this will create a new test inside the feature folder let's open it right here you can see the same test underscore example method which will check if the forward slash uri exists and if it can it will send back a method called a search status which accepts one parameter and in our case we're sending back a 200 which is ok this will pass the test because we do have a forward slash route defined like what showed you before let's run it and test it out let's say php artisan test right here you can see that we created the user test and we have a method called example which has passed the test by the way it will remove the test underscore from the method name so let's change the uri real quick to let's say forward slash test which we do not have defined so we should get an error message inside the cli hit the arrow up and hit enter and right here our first failed test let's screw up and see what the error message is one thing i actually really like about php unit in larval is the error message it sends back not the word fill right here but actually this piece of code that you can't find it's saying that it's expecting a status code of 200 which we have defined but it has received 404 and if you have followed my larval api course you should know that 404 means not found so the route does not exist when working with many tests you'll see that this piece of text right here comes in clutch because it will show you how many tests have either failed or passed alright the command that we performed in order to create our user test created a file inside the feature folder the same command can be used to generate a unit test but we do need to add an additional flag if we hit the arrow up until the make command hit space and add a double dash followed with the text of unit hit enter you will see that the test has been created successfully which might be weird because you already got a user test file like i said this will create a file inside the unit folder as you can see right here rather than the feature folder if we run the php artisan test command again we still have a file so we need to change that actually all right hit the arrow up right here you'll see that our user test file passed from the feature folder which is alright and also from the units folder it's finally time to create a couple tests that aren't as basic as the example larval provides for us now the simplest way to test it is through the authentication scaffolding because it allows us to use the user's model so what we need to do inside the single line is to perform composer require larval for slash ui then with the ui that we just pulled in we can basically say php artisan ui and let's say react we're not going to use a frontend space double dash alt hit enter all right let's run npm install double ampersand npm run dev this might take a second because there are quite some files in here now that we're setting up our stuff let's also create a database so let's say mysql perform the create database and let's call it largo underscore testing write down exit we need to set up our credentials in the emv file my database name is larval underscore testing and my password is dari1234 save it close it off now the last step is to migrate our migrations so let's say php artisan migrate that was a typo all right right now i want to perform a couple simple unit tests inside the usertest.php file from the units folder so let's open it and let me close off the other one let's remove the default one that we got and the first unit that we're going to perform is called public function let's say test underscore login underscore form in here we're going to check if the forward slash login endpoint exists so let's say variable response is equal to this get and what we're going to get is a endpoint or uri of forward slash login on the line below we're going to say response assert status and the status will be 200. as you can see right here we're getting an error message because we are using an undefined method get now there is some kind of bug inside largo which does not recognizes this test case so what we need to do is to say that we want to use test backslash test case and if we scroll down you can see that it recognizes the get method now alright so we're ready to perform our test let's say php artisan test and right here you'll see that our test has passed the login form so what's next what else do we want to test well we can surely test the login validation so right below our test login form let's create a new one let's call it public function test underscore user underscore duplication what we're going to do is to make sure that the user can't have the same name and email and this will automatically be done by larval behind the scenes because we pulled in the authentication scaffolding but it's always a good thing to double check we got to make two users which we will then compare to each other it's not a complete unit test but it's more like an integration test or feature test because usually you'll be interacting with a database so let's create a new user right here so user one is equal to the user model pull it in column column make let's pass in an array inside the make method and hit enter we have a key value pair right here where the key will be the database column so name pointer and we're going to call it let's say john doe and let's do the same thing for the email which will be john doe at gmail dot com let's copy our user one and let's paste it right here and change the variable to user two let's change the name to let's say dari and the email to diary at gmail if we go right below our user too we have to make sure that it asserts something so what we're going to do is to say that this assert true which accepts and condition and what we're going to check is to see if the user1 name is not equal to the name of user 2. save it inside the cli hit the arrow up and run our test scroll up and right here you'll see that user duplication has passed the test this seems like a test you probably won't be creating that often but the main focus on this test is the fact that you can't test a single class or method even when the object under the test are framework connected let's create one more unit test before we continue on right below our method we need to create a new one so let's say public function test underscore delete underscore user right there we're going to create a new user through the factory let's say that we have a new object of user which is equal to the user model column column factory we're going to change the count methods to the factory and we're going to pass in a1 to create one user and we're going to make so what we then can do is to get that object and say that we want to get user column column first so whenever you want to delete a user you obviously get to make sure that the user exists and that can be done through an if statement so let's say if what we're going to do is to see if user even exists and inside the if statement we're going to say well if it does exist delete it for me once again we have to pass an assertion so let's say this object of assert true is true save it let's run our test scroll up and you can see that the lead user has also passed the test all right it's time to move on to the next type of tests which will be hdp testing we have actually seen one of them inside the test login form if we scroll up where we're getting the forward slash login endpoint now we can obviously change this up to the put post patch or delete method as well which will basically sum up all available http methods as you can see on my screen right now every single method accepts an uri as their first param right here we got the get post put patch delete it accepts a uri as the first param which will be the end point of the route the get method accepts an header and the post put patch and delete have a date of array as well now it's also quite important to keep in mind that you do need to return a response object that will represent the http response this will not be the illuminate response object that we are all familiar with but there will be an instance of the illuminate foundation testing test response which is basically a wrapper around the response object with some additional assertions for testing there are more than 40 available assertions method that you can perform on the request object so it will be difficult to cover them all but i will try to go over the most basic and interesting ones alright enough talked let's get back to the code editor and i want to test out one more http request because you understand that the rest of them work in the same exact way if we perform the php artisan route column list command and let me actually make it a little bit bigger and zoom out i hope you can read it i'm not sure you'll see that the register endpoint is a post request so let's create a test for this route let me zoom in make the terminal smaller right at the bottom let's create a new test public function test underscore it underscore stores underscore new underscore users so what we're going to do is to set the response object equal to this post like i've showed you before we got to pass in a uri as the first endpoint or forward slash register comma space brackets hit enter which will be the data array that you also have to pass through when we're going to register an account we got to at least fill in the name we've got the email we got the password and the last one is the password underscore confirmation for the name let's set it equal to dari the email is dari gmail.com give it a password of dari1234 and let's copy it and paste it in the password confirmation right below our post request we're going to return our response object like i showed you a couple minutes ago so response and we're going to chain the assert redirect method and whenever a user is registered we want to send them back to the forward slash home endpoint this should work let's save it and let's go to the terminal let's run php artisan test right here we have no fails and if we scroll up you'll see that the its source new user test has been passed it's time to move into database test larvae offers a lot of tools and assertions in order to make it easier to test your database driven applications we have created a test before where we looked if we could create a user or not to be honest it's not the most efficient way you rather want to make an http call to store your endpoint and then assert to see if that package exists in the database so we have two primary assertions that we can use the first one is the assert database has this will basically look inside the database and sees if data exists which is a value that you have to pass in the second method is the assert database missing as the name implies it's going to check whether a given value is missing in the database now let's dive a little bit deeper into the assert database has methods how does it look in sql think about it you're going to perform a where statement you will pass in a value where my sql will check in the database whether the value exists or not all right i'm done with all the theoretical stuff our uses table is empty at the moment so it can't check if a user exists so we got to make sure that we add a row there i want to do it through a seeder so what we can do is to say php artisan make me a seeder called users table cedar if we open the database folder in the root of our directory seeders and the user's tables either we have a run method where we're basically going to say db pull it in column column table the table name will be in single quotes users we're going to chain the insert method which accepts an array hit enter the name will be dari the email will be dari at oops gmail.com and we have a password which will be the hash method pull the illuminate fake 8 in column column make a new password now the last step is to run our database either so inside the client let me actually save it let's run php artisan db colon seed dash dash class and the class is users table seeder hit enter and we got a typo right here i guess apparently i have a user that's weird mysql use largo underscore testing select all from users that's where it has added it so well let's just perform an exit and let's close off our users tables either and right below our methods right below our last method we need to create a new one so let's say public function test underscore database and in here we're going to say this so we're going to call the assert database has methods now you need to pass in two parameters inside this method the first value will be in single quotes the table name where you want to search in in our case we got to say users because we want to search for a user inside the users table the second param so a comma will be an array with a key value pair so let's say brackets hit enter right here we're going to pass in a key value pair the key will be name in our case because we're going to search to the column with a name of name then we're going to tell our test well look for a value called dory now our cd worked because we have a user inside the database so what we can do is to run our test and right here if we scroll up you can see that the database test has been passed the second method was the assert database missing method so let's replace has with a search database missing let's keep our key value pair as it is right now because we should be getting an error message save it and let's run it all right one test has failed if we scroll up you'll see that the error message says that failed asserting that a row in the table users does not match the attributes so the user does exist if we change it to john save it run our test you'll see that it has been passed the next type of test will be testing our seeders there's a reason why we created the users tables either because we're going to test if that works properly right now if we create a new method right here with the name of public function test underscore if underscore cedars works we're going to perform a command that will test all seeders first it's very simple all we got to do is to say this seed what this will do is actually let me add a comment is seat all seeders in the seeders folder now this command is pretty much equal to php artisan db colon seed save it let's run our test one risked and let's see what the output is this test did not perform any assertions well that's actually true because we're not actually doing anything it's also not an error message which is actually quite good this was it for this video where i showed you the basics of testing in larval in the next video we're going to dive into sessions cash and cookies for now this was it for this video i hope you enjoyed it if you did leave this video a thumbs up and if you're new to this channel please hit the subscribe button
Info
Channel: Code With Dary
Views: 6,847
Rating: undefined out of 5
Keywords: how to start writing tests with laravel, laravel testing code, how to start writing tests with laravel 8, laravel 8 testing tutorial, getting started laravel 8 testing, laravel testing with examples, laravel run specific test, how to do testing in laravel 8, laravel unit testing best practices, start laravel testing, how to unit and feature test your laravel php applications, laravel unit testing, laravel test with php, how to unit test php
Id: UjA-16diixc
Channel Id: undefined
Length: 26min 16sec (1576 seconds)
Published: Mon Sep 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.