我正在使用phpunit测试Zend Framework上的购物车,结帐,付款流程.我正在ShoppingCartController通过向购物车添加产品进行测试,ShoppingCart模型通过将产品ID存储在Zend会话命名空间中来处理产品添加,然后在另一个测试中我想测试产品是否已添加.同一个ShoppingCartModel从同一个Zend Session命名空间变量中检索添加的产品列表.
添加产品测试看起来像这样并且运行良好,并且var_dump($_SESSION)已添加到调试并正确显示产品:
public function testCanAddProductsToShoppingCart() {
$testProducts = array(
array(
"product_id" => "1",
"product_quantity" => "5"
),
array(
"product_id" => "1",
"product_quantity" => "3"
),
array(
"product_id" => "2",
"product_quantity" => "1"
)
);
Ecommerce_Model_Shoppingcart::clean();
foreach ($testProducts as $product) {
$this->request->setMethod('POST')
->setPost(array(
'product_id' => $product["product_id"],
'quantity' => $product["product_quantity"]
));
$this->dispatch($this->getRouteUrl("add_to_shopping_cart"));
$this->assertResponseCode('200');
}
$products = Ecommerce_Model_Shoppingcart::getData();
$this->assertTrue($products[2][0]["product"] instanceof Ecommerce_Model_Product);
$this->assertEquals($products[2][0]["quantity"],
"8");
$this->assertTrue($products[2][1]["product"] instanceof Ecommerce_Model_Product);
$this->assertEquals($products[2][1]["quantity"],
"1");
var_dump($_SESSION);
}
Run Code Online (Sandbox Code Playgroud)
第二个测试尝试通过询问模型来检索产品var_dump($_SESSION),在测试开始时已经为null.会话变量被重置,我想找到一种方法来保存它们,任何人都可以帮忙吗?
public function testCanDisplayShoppingCartWidget() {
var_dump($_SESSION);
$this->dispatch($this->getRouteUrl("view_shopping_mini_cart"));
$this->assertResponseCode('200');
}
Run Code Online (Sandbox Code Playgroud)
很抱歉指向错误的方向.这是一种实现这一目标的更好方法,由irha.freenode.net的#phpunit频道的ashawley建议:
<?php
# running from the cli doesn't set $_SESSION here on phpunit trunk
if ( !isset( $_SESSION ) ) $_SESSION = array( );
class FooTest extends PHPUnit_Framework_TestCase {
protected $backupGlobalsBlacklist = array( '_SESSION' );
public function testOne( ) {
$_SESSION['foo'] = 'bar';
}
public function testTwo( ) {
$this->assertEquals( 'bar', $_SESSION['foo'] );
}
}
?>
Run Code Online (Sandbox Code Playgroud)
== END UPDATE
例如,删除函数setUp()和tearDown()方法时,此测试失败:
<?php
# Usage: save this to test.php and run phpunit test.php
# running from the cli doesn't set $_SESSION here on phpunit trunk
if ( !isset( $_SESSION ) ) $_SESSION = array( );
class FooTest extends PHPUnit_Framework_TestCase {
public static $shared_session = array( );
public function setUp() {
$_SESSION = FooTest::$shared_session;
}
public function tearDown() {
FooTest::$shared_session = $_SESSION;
}
public function testOne( ) {
$_SESSION['foo'] = 'bar';
}
public function testTwo( ) {
$this->assertEquals( 'bar', $_SESSION['foo'] );
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个backupGlobals功能,但它不适合我.你应该试一试,也许它适用于稳定的PHPUnit.