9

I have a basic class GenericHelper.php in directory Foo/BarBundle/Helper

I registered it as a service in Foo/BarBundle/Resources/config/services.yml:

    parameters:
       generic_helper.class: Foo\BarBundle\Helper\GenericHelper

    services:
       generic_helper:
           class: %generic_helper.class%

and I'm able to access it in a command by doing the following:

    $helper = $this->getContainer()->get('generic_helper');

Now, I'd like to unit test that class with PHPUnit; I have the following code (similar to http://symfony.com/doc/2.0/book/testing.html#unit-tests):

    namespace Foo\BarBundle\Tests\Helper;

    use Foo\BarBundle\Helper\GenericHelper;

    class GenericHelperTest extends \PHPUnit_Framework_TestCase {

        public function testSomeMethod() {
            $helper = new GenericHelper(); //line 10
            $this->assertEquals($helper->someMethod(), SOME_RESULT);
        }
    }

Running PHPUnit results in the following error:

    PHP Fatal error:  Class 'Foo\BarBundle\Helper\GenericHelper' not found in /DIR/src/Foo/BarBundle/Tests/Helper/GenericHelperTest.php on line 10

Grepping for 'GenericHelper' only yields a few results:

  • the Class itself and the Test class
  • the services.yml file
  • appDevDebugProjectContainer files in app/cache/dev/, which have all the service getters

Question(s):

  • Does Symfony prevent PHPUnit from directly constructing a service class?
  • Is there a way to do this without creating a Symfony Container then accessing the service (as done here: Access Symfony 2 container via Unit test?)? I mean, it's still just a basic class...
3
  • It should work, you probably have something wrong with the autoloading of your classes. Could you post your phpunit.xml file? Commented Mar 8, 2012 at 16:37
  • @Matt I haven't modified the phpunit.xml.dist file that came with symfony, but your comment helped me out regardless - running phpunit with -c app/ (directory with the dist file) worked. I guess it has to do with the specified bootstrap file within? Anyways, thanks! Commented Mar 8, 2012 at 17:17
  • Yes because bootstrap.php.cache will include the autoloading stuff. You should post an answer to your question and accept it when you will can (I think you must wait something like two days). Commented Mar 8, 2012 at 18:23

1 Answer 1

9

Running phpunit with the -c flag pointing to the directory containing the phpunit.xml.dist file solved the issue. Doing this includes bootstrap.php.cache and therefore the autoloading stuff necessary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.