ルーティングされてるメソッドは基本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);
}
}