在 CakePHP 2.2.5 中有一个组件来处理我的应用程序的付款。我可以从浏览器/常规会话中成功运行组件内的函数“addPayment”,但是当我在测试用例中运行它时它失败了。
$this->controller->Product->getDataSource();
在组件内初始化事务时出现错误“尝试获取非对象的属性” 。
似乎$this->controller
或未$this->controller->Product
在组件中设置。有什么想法可以解决它以使其$this->controller->Product->getDataSource();
有效吗?
应用程序/测试/案例/控制器/组件/财务组件:
App::uses('ComponentCollection', 'Controller');
App::uses('Component', 'Controller');
App::uses('FinanceComponent', 'Controller/Component');
class TestFinanceController extends Controller {
public $uses = array('Product');
}
class FinanceComponentTest extends CakeTestCase {
public $Finance = null;
public $Controller = null;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$CakeRequest = new CakeRequest();
$CakeResponse = new CakeResponse();
$this->Controller = new TestFinanceController($CakeRequest, $CakeResponse);
$Collection = new ComponentCollection();
$this->Finance = new FinanceComponent($Collection);
$this->Finance->startup($this->Controller);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Finance);
unset($this->Controller);
parent::tearDown();
}
/**
* testAddPayment method
*
* @return void
*/
public function testAddPayment() {
// Get products
$products = $this->Controller->Product->find('all', array(
'limit' => 2,
'offset' => rand(2,6)
));
$this->assertEquals(2, count($products));
// hidden code to shorten example...
// Test buying from main store
$values = array(
// hidden code to shorten example...
);
$payment = call_user_func_array(array($this->Finance, 'addPayment'), array_values($values));
}
}
应用程序/控制器/组件/FinanceComponent.php:
class FinanceComponent extends Component {
/**
* Controller instance reference
*
* @var object
*/
public $controller;
public $dataSource;
public $mainUserId = 1;
public $mainStoreId = 1;
/**
* Constructor
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);
$this->controller = $collection->getController();
}
public function addPayment($amount, $amountTax, $userId, $products, $storeId, $transactionId = null, $affiliateUserId = null) {
// Start Transaction
$this->__transactionStart();
try {
// hidden code to shorten example...
// Commit Transaction
$this->__transactionCommit();
return array(
'status' => 'success'
);
} catch (Exception $e) {
// Rollback Transaction
$this->__transactionRollback();
return array(
'status' => 'error',
'message' => 'Error ' . $e->getLine() . ': ' . $e->getMessage()
);
}
}
protected function __transactionStart() {
$this->dataSource = $this->controller->Product->getDataSource();
$this->dataSource->begin();
}
protected function __transactionRollback() {
$this->dataSource->rollback();
}
protected function __transactionCommit() {
$this->dataSource->commit();
}
}