8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cake3 で IntegrationTestCase を使った Controller のテストで、ComponentをMockしたい

Last updated at Posted at 2017-04-13

前提

・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();
    }
}

以上です。

他になにか良さげな方法があったら誰か教えてください!!

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?