David
David

Reputation: 320

Mock a request in phpunit

I am trying to write a unit test (phpunit) to cover a controller action. I am receiving problems regarding invalid scope for the getRequest() call.

note: I am a newbie to Symfony2 and TDD (phpunit)

I guess this is because there is no request as such?

My questions are:

  1. Can I mock a request object?
  2. Am I approaching this in the right way? Should I be placing the bulk of the code into a service and then unit testing the service and only FUNCTIONAL test the controllers?

I think knowing the principle going forward is what I'm after, rather than the lines of code.

Upvotes: 2

Views: 5799

Answers (1)

Jon Winstanley
Jon Winstanley

Reputation: 23311

There is a mock request built into the web test case. Just extend that and use the crawler to make the request.

For example:

public function testMyController()
{
    $client = static::createClient();
    $router = $this->container->get('router');
    $url = $router->generate('routeName');
    $crawler = $client->request('GET', $url);

    // check we get a 200
    $this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for API Config call");
}

Upvotes: 2

Related Questions