atoum / AtoumBundle

This bundle provides a simple integration of atoum into Symfony 2.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Allow to mock services in DIC

mikaelrandy opened this issue · comments

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 ?