Examples of testing methods for PHP scripts _php tips

Source: Internet
Author: User
Tags php script

A common test sample

We often experience this by rewriting a few legacy code that has not been tested, even if the code is written with an Object-oriented object. To test this code, my advice is to break the code into chunks so it's easy to test.

However, these legacy code is not so good refactoring, for example: Before the test, you can not rewrite the code, this is to avoid affecting the original program, of course, it is not good for unit testing.

In a PHP program, a portion of the code is usually written in several index.php and script.php files, which are stored in several different folders. If you do not find their entry points, they cannot be accessed directly by the Web server.

Test copy

To test a PHP script, we need to simulate an HTTP request and check whether the returned response (response) equals the expected value. The attention here is to simulate a request, to define response and requests, not just the different content, but also their header information (header) is different.

Also, if we want to test a transaction script that operates on data, we want to make sure that it doesn't connect to the real database or the rest of the application.

In reality, no one usually takes the original PHP script to rewrite the test. Because of the fear of the code can not be restored. I recommend using a copy of the PHP script so that we can do some minor surgery on the PHP code.

How to make minimal changes to the code: Delete the Include and require statements (if they are not used), and modify the way the internal functions are invoked, for example, to write the header () as $object->header ().

Finally, let's test this transaction script. After testing, we can extract them from the copy script and put them in the new script file.

Specific steps

First, simulate an HTTP request and redefine the variable $_get and $_post, and modify the header of the $_server.

To obtain a request response, the body of the response can be captured by Ob_start () and Ob_get_clean (), which collects each buffer (buffered content) that is output with the echo () or <?php tag.

Note: Output buffering supports nesting at multiple levels of PHP, so in most cases it can be captured even if the script is using the ob_* call itself.

Third, the test script should contain the internal method of the transaction script, so the method within the scope of this script can be invoked. For example:
1. The variables required by the script can be defined as local variables encapsulated, such as $connection as a database connection.
2. Not the original PHP built-in functions, should be added to the object to invoke, such as: Header () written $this->header ().

Specific code

This is the transaction script object we want to test, specifically in the script, we also need to encapsulate:


<?php
class forumposting
{
  Private $headers = Array ();
 
  Public Function HandleRequest ($postRequest)
  {
    $_post = $postRequest;
    $connection = $this->getaconnection ();
    Ob_start ();
    Include ' forum/post_new_copy.php ';
    $content = Ob_get_clean ();
    Return Array (
      ' content ' => $content,
      ' headers ' => $this->headers
    );
  }
 
  Private Function Header ($headerLine)
  {
    $this->headers[] = $headerLine;
  }
   
  ...
}

Here's our test code:

 
Public Function testanewpostiscreated ()
{
  $action = new forumposting ();
  $response = $action->handlerequest Array (
    ' Id_thread ' =>,
    ' text ' => ' Hello, World ',
    ...)
  ));
  $this->assertequals (' ... ', $response [' content ']);
  $this->assertcontains (' content-type:text/html ', $response [' headers ']);
}

The test copy is only temporary! It allows us to write tests that will not change. In the end, we'll refactor the PHP script that has been tested to eliminate redundant code.

When our test is complete, we can replace the contents of HandleRequest () with the real logical code. If you want to write a lot of these test scripts, you can write a generic test object to meet your testing needs.


Second, the PHP Developer Unit Test Kit

In the field of PHP, unit test tools mainly have phpunit,phpunit2 and simpletest three kinds. PHPUnit in the function is very simple, not perfect; PHPUNIT2 is a unit test tool written specifically for PHP5, which is aligned with junit in both structure and function, while simpletest is a very useful test tool. The webtest, which supports testing the Web interface, is one of the most recommended testing tools for easy access. In this article, we select SimpleTest to introduce.

Related knowledge: PHPUNIT2 is also a very good tool, especially in the framework of a lot of punctuate, I hope that in the future will have the opportunity to share in the articles in the special.

SimpleTest: That's simple.

Installation SimpleTest is very simple, on the sf.net download a source package, and then extract to the Web directory can be used, there is not much to say.

Let's take a look at an example: Write a test to check if a Web site can be accessed.

First we introduce the files to use:

Code list:

Require_once (".. /simpletest/unit_tester.php ");
Require_once (".. /simpletest/web_tester.php ");
Require_once (".. /simpletest/reporter.php ");

Then we create a test class:

Code list:

Class Testofsite extends Webtestcase
{
  function testofsite ()
  {
    $this->webtestcase ("test");
  }

  function Testsite ()
  {
    $this->get ("http://howgo.net/prettyface/display.php");
    $this->asserttitle (".: Facebook:.");
  }


First we extend the Webtestcase class so that we can automatically get the ability to test the web, and then in the constructor we use the base class directly, just passing the title to it. Then we should write the test method, which starts with ' test ' to identify which methods in the class are to be invoked when we run the test.

And $this->get will get the content of the webpage, we specify its title as ".: Facebook:." And then what we're going to do is instantiate the object of the class and run it.

Code list:

$test = &new testofsite ();
$test->run (New Htmlreporter ());

Below is the result of the operation:

If the test fails, the bottom interface appears:

A simple test is done here.

Combat Drills – a login test

Here we go to the actual combat, on this basis to complete a login test. This time we'll put out the complete code:

Code list:

Require_once (".. /simpletest/unit_tester.php ");
Require_once (".. /simpletest/web_tester.php ");
Require_once (".. /simpletest/reporter.php ");

Class Testoflogin extends Webtestcase
{
  function testoflogin ()
  {
    $this->webtestcase ("Login Test");
  } 

  function Testloginok ()
  {
    //Get
    the page $this->get ("http://howgo.net/prettyface/login.php");

    Add a test table entry
    $this->setfield ("name", "Easy");
    $this->setfield ("Pass", "Hu Jintao");

    Submit
    $this->clicksubmit ("submit");

    See if the return page is correct
    $this->assertwantedpattern ("/Successful Login/") after submitting;

    Click on the page link
    $this->clicklink ("Click here to enter the admin page");

    View the specified page title and key content
    $this->asserttitle ("ADMINCP");
    $this->assertwantedpattern ("/Please select the task to be performed/");

    Exit login
    $this->clicklink ("Exit Management");
    $this->clicklink
  }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.