CakePHP 2.2.5 には、アプリの支払いを処理するコンポーネントがあります。ブラウザ/通常のセッションからコンポーネント内で関数「addPayment」を正常に実行できますが、テスト ケースで実行すると失敗します。
$this->controller->Product->getDataSource();
コンポーネント内でトランザクションを初期化すると、「オブジェクト以外のプロパティを取得しようとしています」というエラーが表示されます。
コンポーネントに設定されているように見える$this->controller
か、設定されていません。$this->controller->Product
それが機能するように修正する方法はあります$this->controller->Product->getDataSource();
か?
app/Test/Case/Controller/Compnent/FinanceComponent:
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();
}
}