#native_company# #native_desc#
#native_cta#

Testing Forms in PHP with SimpleTest Page 2

By W. Jason Gilmore
on March 2, 2011

Testing Invalid Form Submissions

Web development would be pretty easy if we were concerned only with testing valid form data. Unfortunately, users can be expected to submit all manner of improper, invalid, and even malicious data and so you’ll need to write numerous tests that ensure your PHP code is properly detecting and reporting errant form input such as an invalid email address or missing name. Again when using the Web testing framework you’ll be concerned with ensuring that the appropriate error messages are displayed. Once the form validation code has been added to the page you can use the following tests to ensure valid email addresses and names consisting of at least one character are included with the form submission:

function testInvalidEmailAddress() {
  $this->get('http://www.example.com/contact.php');
  $this->assertResponse(200);

  $this->setField("name", "Jason");
  $this->setField("email", "wjexample.com");
  $this->setField("message", "I look forward to hearing from you!");

  $this->clickSubmit("Contact us!");

  $this->assertResponse(200);
  $this->assertText("Please provide a valid email address.");
}

function testInvalidName() {
  $this->get('http://www.example.com/contact.php');
  $this->assertResponse(200);

  $this->setField("name", "");
  $this->setField("email", "[email protected]");
  $this->setField("message", "I look forward to hearing from you!");

  $this->clickSubmit("Contact us!");

  $this->assertResponse(200);
  $this->assertText("Please provide your name.");
}

Run all of the tests and you should see output similar to that found in Figure 3.
The SimpleTest Framework
Figure 3. Comprehensive Form Testing Is Easy with SimpleTest

Conclusion

SimpleTest’s native Web testing framework makes it ridiculously easy to automate the testing of your PHP logic from the end user’s perspective. This functionality can greatly reduce the time you’ll otherwise need to spend performing tedious tasks such as completing and submitting Web forms. Be sure to check out the following links for more information about Web testing!
  • SimpleTest: The SimpleTest Homepage
  • Selenium: Another great solution for automating Web testing
  • Watir: This Web application testing in Ruby framework is another great tool capable of scripting automated interaction tasks with all major browsers.
What other Web testing tools do you recommend? Tell us about them in the comments!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including “Easy PHP Websites with the Zend Framework”, “Easy PayPal with PHP”, and “Beginning PHP and MySQL, Fourth Edition”. Follow him on Twitter at @wjgilmore.