2012-01-15 34 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()); 
    } 
} 
相关问题