我正在使用 phpunit 在 Zend Framework 上测试购物车、结账、付款流程。我正在测试 ShoppingCartController
通过将产品添加到购物车,ShoppingCart
模型通过将产品 ID 存储在 Zend session 命名空间中来处理产品添加,然后在另一个测试中我想测试产品是否已添加。同ShoppingCart
模型从相同的 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);
}
第二个测试尝试通过要求模型检索产品,
var_dump($_SESSION)
在测试开始时已经为空。 session 变量已重置,我想找到一种方法来保留它们,有人可以帮忙吗? public function testCanDisplayShoppingCartWidget() {
var_dump($_SESSION);
$this->dispatch($this->getRouteUrl("view_shopping_mini_cart"));
$this->assertResponseCode('200');
}
最佳答案
很抱歉将您指向错误的方向。这是a way better way实现这一点,由来自 irc.freenode.net 的 #phpunit channel 的 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'] );
}
}
?>
== 结束更新
例如,当您删除函数 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'] );
}
}
还有一个backupGlobals feature但这对我不起作用。您应该尝试一下,也许它适用于稳定的 PHPUnit。
关于session - 如何通过phpunit上的所有测试保留 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370927/