Search code examples
phpunit-testingselenium-webdriverfunctional-testing

Create a unit or functional php test automatically by simulating it on browser


As title says, Is there anyway I can create unit or functional test automatically by just simulating it once or more in browser?

I was thinking about something like iMacros addon in firefox, we can record our clicks on any element and it automatically creates the macro. But instead I want to parse those macro lines into php code lines.

Well, basically this makes more sense if the question is like 'Is there anyway to auto generate php code by simulating it on browser'

Is it possible?


Solution

  • Yes there is. There are several tools designed for exactly this kind of thing.

    You should take a look at Selenium and Sahi to begin with. Both of these tools allow you to record a sequence of actions in any of the major web browsers, and replay it back automatically as a test script.

    Both Sahi and Selenium can be integrated with PHP testing frameworks. I've had success in the past with Mink. However there's no real need to use anything related to PHP for functional testing, as the browser environment is completely separate from your PHP back-end, so you could just as easily stick with Sahi/Selenium's native scripting tools.

    Please note, however, that you will be very likely to need to modify by hand the script once it's been generated, as the recording process doesn't always register things in the ideal way. For example, if the recording script picks up unique IDs in the site, those IDs may be different the next time the script runs, and so the script will fail. This is referred to as the test being "brittle", and is a very common problem with automated tests that are recorded in this way.

    Also note that tests of this kind are absolutely not unit tests. The are functional tests. In order to test your system properly, you should be writing unit tests in addition to (or even in preference over) having functional tests.

    Finally, it's worth noting that functional tests do tend to be very slow to run. They're simulating a real-life user experience, so you have to take page loading time into account. If you want to fully test your system with a reasonably sized functional test suite, the tests will take a significant length of time to run (I've seen sites where the functional tests take over an hour to complete, and I'm sure there are others out there that take even longer). This means that it becomes impractical to run the full set of functional tests every single time you change anything.

    This is another reason why a good unit test suite is also important; even a system with thousands of unit tests can generally run the entire set in under a minute. This means you can run the tests for yourself as you change things, so you can see instantly when things break. Functional tests can't do this for you as easily.