From the course: Writing and Refactoring Testable PHP
Automated testing - PHP Tutorial
From the course: Writing and Refactoring Testable PHP
Automated testing
- [Instructor] Automated testing is the process of creating statements of fact about your code. This means that if you make a change that violates those facts, you'll know. I want to illustrate this idea very simply. I'm going to create a simple add function. So first, a new file, and we'll declare strict types. This function expects two integers and it will return an integer and will return x plus y. To demonstrate this function, I'll call it with five and two and echo the output and run it through the interpreter and we see seven. This is not revolutionary code, I realize. Next, I'm going to composer install a package called PHP Unit. More on that in future videos. But the important thing to know that PHP unit is a test framework. That means that it provides functionality you need to test your code. Now that the testing framework is installed, I'm going write a test. We're testing a simple function, so my test is going to be as simple as well. First, I'll create a test directory. Then I'm going to create a new PHP class called Add_Test. And for this to work, I need it to extend test case and we're going to need to import that. Now I'm going to add the setup method, and I am not going to go into too many details here, but this allows for any pretest work to be done. In this case, I have not created any autoloader, so I'm going to require the example file so I can access the add function. So we'll call the parent. Now, I'll write the first test. I'm going to call the test test_add_function, and I'm going to write an assertion, assertEquals, I'm going to say four is the equivalent of two plus two. I can now run this test using vendor/bin/phpunit and telling it where to run. It'll also help if I spell vendor correctly. And this tells me I have one passing test with one assertion. Very cool. To review, I've created normal code for this add function, I included a testing framework with composer, and I've written one assertion inside one test. While simple, this is very instructive. By itself, this test has no value. It, like all PHP code, has to be executed to actually do anything. Writing tests that aren't executed often doesn't provide a lot of value. Also, I'd like to point out this test is not complete. The single assertion assumes perfect intentions. What happens if you add an emoji and a string or a float and an object? Because I type hinted the ARGs and the response, those aren't valid test cases. I don't need to test PHP internal logic. Only my own. Very simply, automated tests are code that document how the code in your project should behave. Automated tests can help prevent regressions, but only if there are tests that cover that particular regression.