PHP Design Pattern Introduction of programming Usage 1th/3 page _php Tips

Source: Internet
Author: User
Tags assert constant rand

Many of the programming idioms summarized here are well worth doing as a separate chapter, or even a book. You should take this chapter as a description of the PHP pattern design using idiomatic methods, and look at some of the listed reference books for more in-depth study.

Test your code

There may not be any code idioms that are more important than the test code. Good testing can increase the speed of development.

Perhaps at first, this proverb contradicts your intuition. You may assert that testing is a barrier to freedom. In fact, on the contrary, if you run those tests quite completely to check the public interface of your software, you may be able to change the internal execution of your system without altering (or worse, damaging) the original application. Test and verify the accuracy and correctness of your public interface, and let yourself change the intrinsic work of some code to make sure that your software is correct and that there are no bugs (errors).

Before we discuss more about the benefits of testing, let's look at an example. All of the test examples in this book use the PHP test framework--simpletest. This test framework can be obtained in http://simpletest.org .

Consider the following code

<?php
PHP4
The subject Code
Define (' Tax_rate ', 0.07);
function Calculate_sales_tax ($amount) {
Round ($amount * tax_rate,2);
}
Include Test library
Require_once ' simpletest/unit_tester.php ';
Require_once ' simpletest/reporter.php ';
The test
Class Testingtestcase extends Unittestcase {
function testingtestcase ($name = ' ") {
$this->unittestcase ($name);
}
function Testsalestax () {
$this->assertequal (7, Calculate_sales_tax (100));
}
}
Run the test
$test = new Testingtestcase (' Testing unit test ');
$test->run (New Htmlreporter ());

The above code first defines a constant--tax_rate, and a function that calculates the sales tax. The code then contains the prerequisites for using the SimpleTest framework: the monomer test itself and a "reporter" module to display the test results.

Class Testingtestcase The Unittestcase class that inherits from the SimpleTest framework. By extending Unittestcase, all methods in class testingtestcase that start with test will be considered test instances--creating conditions to debug your code and assert the result.

Testingtestcase defines a test, testsalestax (), which contains an assertion function assertequal (). If its first two input parameters are equal, it returns true, otherwise it returns false. (If you want to display assertequal () failure information, you can pass in three parameters like this $this->assertequal (7,calculate_sales_tax), "the sales tax Calculation failed ")).

The last two lines of the code create the entity of the test instance and run it using a htmlreporter. You can access this web page to run this simple test.

Running this test will display the test name, the details of the failure assertion, and a summary bar. (green means success (all assertions are passed), while Red implies failure (at least one assertion fails))

(assertion) is a common debugging method in software development, which is supported in many development languages. Assertion In an implementation, assertion is a statement in a program that checks a Boolean expression, and a correct program must guarantee that the Boolean expression evaluates to true; if the value is False, the program is already in an incorrect state. The system will give a warning or exit. Generally speaking, assertion is used to guarantee the most basic and critical correctness of a program. Assertion checks are typically opened during development and testing. To improve performance, the assertion check is usually turned off after the software is released. )

Note: (assertion) is a common debugging method in software development, which is supported in many development languages. In an implementation, assertion is a statement in a program that checks a Boolean expression, and a correct program must guarantee that the Boolean expression evaluates to true; if the value is False, the program is already in an incorrect state. The system will give a warning or exit. Generally speaking, assertion is used to guarantee the most basic and critical correctness of a program. Assertion checks are typically opened during development and testing. To improve performance, the assertion check is usually turned off after the software is released. )

The above code has a (intentional) error, so the run is not passed, the results are as follows:

Calculate_sales_tax () What's wrong with a simple one-line function? You may have noticed that this function does not return a result. The following are the correct functions:

function Calculate_sales_tax ($amount) {
Return round ($amount * tax_rate,2);
}

After the modifications are run, the test passes.

But a simple test does not guarantee that the code is stable. For example, you can change the calculate_sales_tax () to function Calculate_sales_tax ($amount) {return 7;}, the code will pass the test, but only if 1 dollars is equivalent to 100 of the time is correct. You can add some additional test methods yourself to test other static values.

function Testsomemoresalestax () {
$this->assertequal (3.5, Calculate_sales_tax (50));
}

or change the function testsalestax () to verify the second (and third, etc.) values, as shown below

function Testsalestax () {
$this->assertequal (7, Calculate_sales_tax (100));
$this->assertequal (3.5, Calculate_sales_tax (50));
}

So far there is a better way to add a new test: Select the immediate value to test your code. Specifically as follows:

function Testrandomvaluessalestax () {
$amount = rand (500,1000);
$this->asserttrue (defined (' tax_rate '));
$tax = round ($amount *tax_rate*100)/100;
$this->assertequal ($tax, Calculate_sales_tax ($amount));
}

Testrandomvaluessalestax () introduces the method Asserttrue (), if the first variable passed is equal to the Boolean true Asserttrue (). (As with Method Assertequal (), Method Asserttrue () returns a failed message after accepting an optional, extra). So Testrandomvaluessalestax () first thinks that the constant tax_rate has been defined, and then uses this constant to compute the randomly selected amount of tax.

But Testrandomvaluessalestax () also has a problem: it relies heavily on method Calculate_sales_tax (). Tests should be independent of the specific implementation details. A better test should only establish a reasonable dividing line. The next test assumes that the sales tax will never exceed 20%.

function Testrandomvaluessalestax () {
$amount = rand (500,1000);
$this->asserttrue (Calculate_sales_tax ($amount) < $amount *0.20);
}

Ensuring that your code is working properly is the primary purpose of the test, but when testing your code, you should realize that there are additional, relatively minor purposes:

    1. Test the code that allows you to write easy to test. This makes the code loosely coupled, complex, and well modular.
    2. The test will give you a clear idea of the expected results of the running code, so that you can focus on the design and analysis of the module from the outset. Passing the test will also allow you to consider all possible inputs and corresponding output results.
    3. Testing can quickly understand the purpose of coding. In other words, Test Cases act as "instance" and "document" functions, showing exactly how to build a class, method, and so on. In this book, I sometimes use a test case to demonstrate the expected functionality of the code. By reading the declaration of a test method, you can clearly understand how the code works. A test instance is defined as the operation of the code under the explicit usage.

Finally, if your test set--the set of test instances--is very thorough, and when all the tests are passed, you can say that your code is complete. Interestingly, this view also happens to be one of the features of test driven Development (testing-driven development).

Test driven Development (TDD) is also considered the test first coding (pre-coded test). Test first coding is a way to take tests one step further: Write a test before you write any code. You can download from http://xprogramming.com/xpmag/testFirstGuidelines.htm to a nice, concise summary of TDD, and download it to a good primer on strategy "Test driven development:by Example" in Kent Beck's book (the example of this one is developed in Java, but the readability of the code is good, and the introduction and description of the topic is good).

Note: Agile Development (Development Agile)
Recently, monomer testing-especially mapping-driven development-has been closely linked to agile development methodologies, such as extreme Programming (XP). The focus of extreme programming is on fast, repetitive, functional code to customers, and changing customer requirements as a necessary part of the development process. Here are some online resources for learning Agile Programming:
Functional Testing
Most of the test examples in this book are used to test the object-facing code, but all forms of programming can be harvested from it. Individual test frameworks, such as phpunits and SimpleTest, can also be easily tested for functional functions. For example, the simpletest example above, it is used to test the Calculate_sales_tax () function. Program members around the world: put a single test case into your library of functions!

I hope that after the discussion above, you will also be driven-"test infected"! (This term, original to Erich Gamma, see article http://junit.sourceforge.net/doc/testinfected/testing.htmfor details), as Gamma wrote, At first you may feel that testing is tedious, but when you build a broad test set for your program, you will be more confident in your code!

Current 1/3 page 123 Next read the full text

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.