The pseudo object pattern introduced in the PHP design pattern

Source: Internet
Author: User

Object-oriented programming is rich and colorful, partly because of the interaction between objects. A single object can encapsulate a complex subsystem so that complex operations can be simplified by the invocation of some methods. (An ubiquitous database connection is one such instance of an object.) )

However, it is often the case that the interactivity between objects is so complex that we have to confront the vexed question of "chicken or Egg First": How to create and test an object that relies on many created objects or on other things that are difficult to realize, such as the creation and testing of the entire database.

Problem

How do I separate and test a piece of code that is related to other objects and resources? How do you create one or more objects, programs to verify that your code works?

Solution

When testing an object with situ (or in a simulated program environment) is expensive or difficult, pseudo objects can be used to simulate this behavior. Pseudo objects have the same interface as real objects, but can provide precompiled responses, track method calls, and validate call order.

Pseudo objects are the "special forces" of testing. They are secretly trained, infiltrated into the target code, simulate and monitor communication methods, and return results. Pseudo objects help find and eliminate program vulnerabilities and support more "hazard" operations in normal debugging environments.

Note: the Serverstub

The pseudo object pattern is an extension of another test pattern serverstub. The serverstub mode replaces a resource and returns the corresponding value that is invoked by its method. Serverstub becomes a pseudo object when it participates in the invocation of the method in the specified order.

It is not a design pattern

This chapter differs from other chapters because the pseudo object is a test pattern rather than a design pattern. This is similar to an additional chapter, but the use of it is certainly worth incorporating into the coding process. Another difference is that we no longer focus on the basics of how this pattern is encoded, but rather on how to use pseudo objects in simpletest.

This chapter first presents a very simple example to demonstrate the basic mechanism of pseudo objects under SimpleTest. Then show you how to use pseudo objects to help refactor existing code and how to test a new solution.

Sample code

A pseudo object is a substitute for an object in a test, and it is easier to test the code with it. For example, instead of a real data connection-a real data connection that cannot be physically connected for some reason-you can create a pseudo object to simulate. This means that the pseudo object needs to accurately respond to the same application interface that is invoked in the code.

Let's create a pseudo object instead of a simple class named Accumulator, which is a summation class. The following are the original accumulator classes:

PHP4

class Accumulator {
var $total=0;
function add($item) {
$this->total += $item;
}
function total() {
return $this->total;
}
}

The Add () function in this class first accumulates the value into the $total variable, and then the total () function returns. A simple summation can also be as follows (the following code is written as a function, but it can also be written as a class).

function calc_total($items, &$sum) {
foreach($items as $item) {
$sum->add($item);
}
}
function calc_tax(&$amount, $rate=0.07) {
return round($amount->total() * $rate,2);
}

The first function calc_total () uses an additive action to find the sum of a series of values. Here's a simple test:

class MockObjectTestCase extends UnitTestCase {
function testCalcTotal() {
$sum =& new Accumulator;
calc_total(array(1,2,3), $sum);
$this- >assertEqual(6, $sum->total());
}
}

Let's focus on the second example. It would be a costly assumption to realize a true cumulative action. It's a good idea to replace it with a simple object and respond to the relevant code. Using SimpleTest, you can create a pseudo cumulative action with the following code:

In order to use pseudo objects, it is a typical practice to write a new class yourself (not required to do it right away). Fortunately, SimpleTest has an easy way to implement the Mock::generate () method.

In the above example, this method creates a class called Mockaccumulator to respond to all accumulator classes. In addition, the pseudo additive action has other means to manipulate instances of the pseudo object itself. such as Setreturnvalue (). Gives a method name and a value,

Setreturnvalue () can change the pseudo object and give the value called by the corresponding method. Therefore, this statement $amount->setreturnvalue (' Total ', 200) returns 200 regardless of when the total () method is invoked.

Once the initialization is done, you can pass the Mockaccumulator class to the Calc_tax () function to demonstrate an action in the real accumulator object space.

If you stop here--you use an object to return the "encapsulated" response of the called function--you're just using the serverstub pattern. The invocation of a pseudo object to validate a method is not limited to this, because it can be unlimited in order and number of times.

Here is an example of validating a "data flow" through an object:

class MockObjectTestCase extends UnitTestCase {
// ...
function testCalcTax() {
$amount =& new MockAccumulator($this);
$amount->setReturnValue(‘total’,200);
$amount->expectOnce(‘total’);
$this->assertEqual(
14, calc_tax($amount));
$amount->tally();
}
}

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.