Kevin
Kevin

Reputation: 1133

How to get unit test bundle classes that contain dependencies

I have a Symfony 2 project and a few custom classes (services) defined that contain dependencies on other services. I can't figure out how to test my classes using the service container. For example I have the following class;

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

class TextHelper {

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

Now in my unit test I extend \PHPUnit_Framework_TestCase as I would in any other situation, but how can I test my TextHelper class that has dependencies? Can I define my services in a new services_test.yml file? If so, where should it go?

Upvotes: 1

Views: 450

Answers (1)

David Harkness
David Harkness

Reputation: 36562

I haven't used Symfony 2 before, but I would expect that you could create the necessary dependencies--or better, mock objects--and place them into a container for each test.

As an example, say you want to test TextHelper::spellCheck() which should look up each word using a dictionary service and replace any that are incorrect.

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

Upvotes: 2

Related Questions