Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16676

Symfony/PHPUnit mock services

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?

Upvotes: 4

Views: 5342

Answers (1)

l3l0
l3l0

Reputation: 3393

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

Upvotes: 4

Related Questions