Examples of PHP script test methods, detailed script test method _php Tutorial

Source: Internet
Author: User

For example, the test method of PHP script, detailed script test method


I. Common test examples

We often encounter this situation by rewriting some legacy code that has not been tested, or even the code is written in object-oriented. To test this code, my advice is to break the code down into chunks so that it's easy to test.

However, these legacy code is not so well refactored, such as: Before testing, you cannot rewrite the code, in order to avoid affecting the original program, of course, the unit test is not good.

In PHP programs, there is usually a part of the code written in several index.php and script.php files, these. php files are stored in several different folders. If they do not find their entry point, 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 that the returned response (response) is equal to the expected value. The note here is to emulate a request, to define response and request, which is not only the content, but also the header information (the header) is different.

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

In reality, no one usually takes the original PHP script to rewrite the test directly. For fear of making the code unrecoverable. 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 invocation method of the inner function, for example: Write the header () as $object->header ().

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

Specific steps

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

Second, GET request response, response body can be captured by Ob_start () and Ob_get_clean (), it can collect each buffer (buffer content) with echo () or output with the <?php tag.

Note: Output buffering supports multiple levels of nesting in 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 that the method within the scope of this script can be called. For example:
1. The variables required for the script can be defined as local variables encapsulated, such as $connection as a database connection.
2. Not the original PHP built-in function, should be added to the object to invoke, such as: Header () written $this->header ().

Specific code

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


<?phpclass 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 is 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 do not change. In the end, we'll refactor the PHP scripts that have been tested to eliminate redundant code.

When our tests are complete, you can replace the contents of HandleRequest () with the actual logic code. If you want to write a lot of these test scripts, you can write a generic test object to meet your test needs.


Second, the PHP Developer's Unit Test toolkit

In the PHP field, the unit testing tools are mainly phpunit,phpunit2 and simpletest three kinds. The phpunit is very simple in function, not perfect; PHPUNIT2 is a unit test tool written specifically for PHP5, which is both structurally and functionally aligned to JUnit, while SimpleTest is a very useful test tool The webtest, which supports testing the Web application interface, is the most recommended test tool for easy. In this article, we select SimpleTest for introduction.

Related knowledge: PHPUNIT2 is also a very good tool, especially the architecture has a lot to punctuate, I hope that in the future will have the opportunity to share with you in the special article.

SimpleTest: That's simple.

Install simpletest is very simple, on the sf.net download a source package, and then extracted 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 site is accessible.

First we introduce the files to be used:

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 we use the base class directly in the constructor, just pass the title to it. Then we should write the test method, and the test method starts with ' test ' to identify which methods in the class are called when we run the test.

And $this->get will get the content of the page, we specify it titled ".: Facebook:.", and then all we have 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 there is a test error, the following interface appears:

Here a simple test is done.

Combat Drills – a login test

Below we enter the actual combat, on this basis to complete a login test. This time we are going to put 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 page    $this->get ("http://howgo.net/prettyface/login.php");    Add a test table entry    $this->setfield ("name", "Easy");    $this->setfield ("Pass", "******");    Submit    $this->clicksubmit ("submit");    See if the page returned after submission is correct    $this->assertwantedpattern ("/Successful Login/");    Click on the page link    $this->clicklink ("Click here to access 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  }}


http://www.bkjia.com/PHPjc/1043237.html www.bkjia.com true http://www.bkjia.com/PHPjc/1043237.html techarticle For example, the test method of PHP script, detailed script test method One, common test examples We often encounter this situation: some have not been tested by the legacy code to be heavy ...

  • Related Article

    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.