3
3

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.

symfony2.1でルーティングされてないcontrollerのメソッドをテストする時

Posted at

ルーティングされてるメソッドは基本clientクラスを作って実際にHTTPリクエストをしてhtmlを解析してテストしますが、ルーティングされてないメソッドはHTTPリクエストを介してはテストできないので、controllerクラスをインスタンス化してテストします

BlogControllerTest.php
<?php
namespace My¥Bundle¥Test¥Controller;

use My¥Bundle¥Controller¥BlogController;
use My¥Bundle¥Entity¥Blog.php
use Symfony¥Bundle¥FrameworkBundle¥Controller¥Controller;
use Symfony¥Component¥HttpFoundation¥Response;
use Symfony¥Component¥HttpKernel¥Exception¥NotFoundHttpException;

class BlogControllerTest extends WebTestCase
{
    protected $blogController;

    public function setUp()
    {
        $kernel = static::createKernel();
        $kernel->boot();

        $this->blogController = new BlogController();
        $this->blogController->setContainer($kernel->getContainer());
    }

    // controllerクラスにwidgetActionが定義されていてかつ戻り値にResponseクラスが返るメソッドのテスト
    public function testWidgetAction()
    {
        $response = $this->blogController->widgetAction();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
    }

    // controllerクラスにprotectedなgetBlogが定義されていてかつ戻り値にオブジェクトが返ってくるまたは例外がthrowされるメソッドのテスト
    protected function testGetBlog()
    {
        $class = new \ReflectionClass($this->blogController);
        $method = $class->getMethod('getBlog');
        $method->setAccessible(true);

        // 例外が投げられる場合のテスト
        $is_ok = false;
        try {
            $method->invoke($this->blogController, 0);
        } catch (NotFoundHttpException $e) {
            $is_ok = true;
        }
        $this->assertTrue($is_ok);

        // オブジェクトが返ってくる場合のテスト
        $blog = $method->invoke($this->blogController, 1);
        $this->assertInstanceOf('Blog', $blog);
    }
}
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?