前提
・Cakephp 3.3 で IntegrationTestCase を継承したテストを実行する
・Component をどうしてもMockしたい
経緯
・以下のようなテストを書いたが、どうしても 独自AuthComponentのメソッドをモックしたくなった。
class RFMatrixControllerTest extends IntegrationTestCase
{
public function setUp()
{
parent::setUp();
$this->configApplication(null, [CONFIG]);
}
public function test_テスト()
{
$this->get('/test');
$this->assertResponseOk();
}
}
解決方法
・IntegrationTestCase::get が呼ばれる直前に controllerSpy が呼ばれるので、このメソッドをOverideして、
その中でComponentをMockしてやる
class RFMatrixControllerTest extends IntegrationTestCase
{
public function setUp()
{
parent::setUp();
$this->configApplication(null, [CONFIG]);
}
public function controllerSpy($event, $controller = null)
{
parent::controllerSpy($event, $controller);
if (isset($this->_controller)) {
$componentRegistory = new ComponentRegistry($this->_controller);
$MyAuth = $this->getMockBuilder('App\Controller\Component\MyAuthComponent')->setMethods(['identify', 'user'])->setConstructorArgs([$componentRegistory, []])->getMock();
$MyAuth->expects($this->any())->method('identify')->will($this->returnValue(['email' => 'test@test.com']));
$MyAuth->expects($this->any())->method('user')->will($this->returnValue(['email' => 'test@test.com']));
$this->_controller->MyAuth = $MyAuth;
}
}
public function test_テスト()
{
$this->get('/test');
$this->assertResponseOk();
}
}
以上です。
他になにか良さげな方法があったら誰か教えてください!!