4

I'm writing functional tests for Symfony w/ PHPUnit, and my mocks aren't working. It's possible I misunderstood how they work though.

In my unit test's setUp() method I have this code:

...
// Create a stub
$stub = $this->getMockBuilder('\\ApiBundle\\Util\\WordPressBridge')
    ->disableOriginalConstructor()
    ->getMock();

// Configure the stub.
$user = new WordPressUser();
$user->setUsername('dummy');
$stub->expects($this->any())
     ->method('checkCredentials')
     ->will($this->returnValue(true));
$stub->expects($this->any())
     ->method('getUser')
     ->will($this->returnValue($user));
...

In my Symfony application, I have a service defined:

services:
    api.wp_bridge:
        class: ApiBundle\Util\WordPressBridge
        arguments: [@service_container]

It's my understanding that the mock should be replace the real WordPressBridge, but that isn't what's happening. My original is still being used. Am I missing something?

1
  • “Functional unit tests” is an oxymoron. Commented Feb 24, 2013 at 18:43

1 Answer 1

4

It's my understanding that the mock should be replace the real WordPressBridge, but that isn't what's happening. My original is still being used. Am I missing something?

Basically you have to replace your service somehow in the Symfony Container.

If you doing "functional testing" then probably you should create test "dummy" service for "test" env which will overwrote original one. You can do something like that:

in src/YourBundle/Resources/config/services.yml

services:
    api.wp_bridge:
        class: %api.wp_bridge.class%
        arguments: [@service_container]

in app/config/config.yml

parameters:
    api.wp_bridge.class: "ApiBundle\Util\WordPressBridge"

in app/config/config_test.yml

parameters:
    api.wp_bridge.class: "ApiBundle\Util\TestWordPressBridge"

Then functional test will use "ApiBundle\Util\TestWordPressBridge" - cause it is executed in "test" env.

You can try to mock container and pass it to test kernel but this can be painfull without some other mocking lib (in pure PHPUnit).

Personally I am using phpspec2 for "unit" testing where mocking is just easy :) and for some "acceptance criteria" stuff I am using behat and mink

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.