When you’re working with legacy code some times you need to add testing to an additional piece of form processing that has no tests. I find it helpful to break out the form processing code into it’s own class so it’s easier to test but if you’re not lucky it could be a large complicated form with lots of options so setting up a test case can be difficult. var_export is an excellent solution to get the posted data out so you can use it.
var_dump outputs information about a variable that are helpful for debugging but var_export outputs a parsable string of a variable so it can be reused in PHP.
So how do we use this for testing?
Let’s look at this following example:
1. Create a Test
First things we want to do is create a test with a basic check to make sure we’re on the right path:
2. Generate Some Test Data
Next we need to generate some test data. I do this by filling out the form with every weird option that might exist. Then inside the controller I add three lines:
In our example this looks like:
Then we’ll copy and paste the output directly into our test:
3. Break Out the Form Processing Logic
Next we need to create a new function in our ItemFormProcessorFromExistingForm class to process the data and insert it into the controller.
4. Get Your Test Running
Now that we have the function broken it’s own function it’s important to make sure it the test is running. In a lot of cases you might need to setup instances of additional classes (maybe the logged in user?). The important thing is to get the test running
5. Make Sure You Aren’t Missing Any Critical Code
The next step is to generate a code coverage report on the tested function and verify you’re covering all the important parts. I try to get to at least 90% code coverage and make sure all the weird looking parts are covered.
Now it’s time to clean up the legacy code!
Like this post? Don't forget to follow us on Twitter and Facebook for updates.