From the course: Refactoring with GitHub Copilot
Refactoring and automated testing - Github Copilot Tutorial
From the course: Refactoring with GitHub Copilot
Refactoring and automated testing
You know that you and your team probably don't write enough tests, and that's okay. Most people don't. But Copilot can help. To be clear, this is about using AI to support traditional automated testing. The first step to adding tests is finding the right things to test. Not all functions or classes are in a testable state. Identifying the right place to start will help you continue to write tests once you get going. Asking Copilot to write tests for a function or method is a way to quickly see how complex the tests will be. This looks fairly straightforward. A tip though, usually the first test I write in every app is a test that true = true. This is so I can test that the test suite harness is correctly configured. From there, I can be confident that as I add tests and assertions, there will be value in running them. And this is that test. I need a composer install. Okay. Now I can use TestCase. And I will assertTrue is true. Now to run the tests, PHPUnit tests. And no surprise, it passes. Now I'll go ahead and copy the tests that it generated for the alphabetized_by_name() function. And I will create a new file. I'm calling it testable code because it's testing the functions in the TestableCode file. And I will paste. I haven't reviewed this code, I'm just going to blindly run the tests. Ah, and they don't pass because I have not included the file under test. Public function set up. And we'll run again. Oh. Great. And they pass. The seven is a result of output that's hard-coded calling this function. Okay. So I have one, two, three tests, all with one assertion that Copilot generated. I'm going to delete these and do something a little bit easier to demonstrate, though. Well, I was going to type public function testAdd, but I'll auto-complete and take what Copilot has. And now we have two passing tests. A key idea in writing tests is creating the test first so that it fails. I'm going to do that here. I'll type public function testSub. Of course, Copilot auto-completed the assertion. However, it's calling a function that doesn't yet exist. If I jump over to testable code, though, Copilot cannot wait to generate that function for us. It has the context from the test, so it can generate the function. If you feel like test coverage is lacking in your project, and it probably is, there is no faster way to move forward than to work iteratively with Copilot to grow your test coverage.