Skip to content
This repository was archived by the owner on Jul 2, 2026. It is now read-only.
This repository was archived by the owner on Jul 2, 2026. It is now read-only.

Allow to mock services in DIC #81

Description

@mikaelrandy

When testing controllers with AtoumBundle, we need to test some failure use case to check all the behavior of the controller.

Exemple :

/**
 * Status controller
 */
class StatusController extends Controller
{
    /**
     * Status action
     *
     * @return Response
     */
    public function getStatusAction()
    {
        try {
            $this->get('some.service')->someMethod();
        } catch (\Exception $e) {
            return new Response($e->getMessage(), 500, ['content-type' => 'text/plain']);
        }

        return new Response('OK', 200, ['content-type' => 'text/plain']);
    }
}

I want to test each use case of this controller : service is up, and service is down.
So, i want to write something like this :

use atoum\AtoumBundle\Test\Controller\ControllerTest;

/**
 * StatusController test
 */
class StatusController extends ControllerTest
{
    /**
     * Test getStatusAction
     */
    public function testGetStatusAction()
    {
        $this
            ->given(
                $client = static::createClient(),
                $crawler = $client->request('GET', '/status'),
                $response = $client->getResponse()
            )
            ->then
                ->integer($response->getStatusCode())
                    ->isEqualTo(200)
                ->string($response->getContent())
                    ->isEqualTo('OK')
        ;

        $mock = new \mock\Some\Service();
        $mock->getMockController()->someMethod() = function() {
            throw new \Exception('Oops!');
        };

        $this
            ->given(
                $client = static::createClient(),
                $client->getKernel()->setService('some.service', $mock),
                $crawler = $client->request('GET', '/status'),
                $response = $client->getResponse()
            )
            ->then
                ->integer($response->getStatusCode())
                    ->isEqualTo(500)
                ->string($response->getContent())
                    ->isEqualTo('Oops!')
        ;
    }
}

Possible ?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions