2012-01-15 4 views
1

私はSymfony 2プロジェクトと、他のサービスへの依存関係を含むいくつかのカスタムクラス(サービス)を定義しています。サービスコンテナを使用してクラスをテストする方法を理解できません。たとえば私は次のクラスを持っています。私は他のどのような状況で同じよう依存関係を含む単体テストバンドルクラスを取得する方法

namespace My\FirstBundle\Helper; 
use Symfony\Component\DependencyInjection\ContainerInterface; 

class TextHelper { 

    public function __construct(ContainerInterface $container) { 
//.. etc 

は今私のユニットテストでは、私は\ PHPUnit_Framework_TestCaseを拡張しますが、どのように私は依存関係を持っている私のTextHelperクラスをテストすることができますか?新しいservices_test.ymlファイルでサービスを定義できますか?もしそうなら、どこに行くべきですか?

答えて

2

以前はSymfony 2を使用していませんでしたが、必要な依存関係を作成することができます。より良い方法でオブジェクトを模倣し、テストごとにコンテナに配置することができます。

たとえば、TextHelper::spellCheck()をテストして、辞書サービスを使用して各単語を検索し、正しくないものを置き換えるとします。

class TextHelperTest extends PHPUnit_Framework_TestCase { 
    function testSpellCheck() { 
     $container = new Container; 
     $dict = $this->getMock('DictionaryService', array('lookup')); 
     $dict->expects($this->at(0))->method('lookup') 
       ->with('I')->will($this->returnValue('I')); 
     $dict->expects($this->at(1))->method('lookup') 
       ->with('kan')->will($this->returnValue('can')); 
     $dict->expects($this->at(2))->method('lookup') 
       ->with('spell')->will($this->returnValue('spell')); 
     $container['dictionary'] = $dict; 
     $helper = new TextHelper($container); 
     $helper->setText('I kan spell'); 
     $helper->spellCheck(); 
     self::assertEquals('I can spell', $helper->getText()); 
    } 
} 
関連する問題