0

I'm using Symfony 3.3 and PHPUnit 5.7 and I'm trying to mock a service for testing an api controller.

The controller:

class ApiTestManager extends BaseApiController{
    public function getAction(): View
    {
        $response = $this->get('app.business.test_api')->getResponse();
        return $this->view($response);
    }}

The test class:

class ApiTestManagerTest extends WebTestCase {
public function testApiCall()
{
    $client = static::createClient();

    $service = $this->getMockBuilder(ApiTestManager::class)
        ->disableOriginalConstructor()
        ->setMethods(['getResponse'])
        ->getMock()
        ->expects($this->any())
        ->method('getResponse')
        ->will($this->returnValue(new Response()));

    $client->getContainer()->set('app.business.test_api', $service);
    $client->request('GET', 'de/api/v1/getResponse');

    $this->assertEquals(200, $client->getResponse()->getStatusCode());
}}

I've spent hours in trying to find the mistake, but everytime I execute this test it gives me following error:

Error: Call to undefined method PHPUnit_Framework_MockObject_Builder_InvocationMocker::getResponse()

Can anyone tell me whats wrong with my code? Thanks :)

2
  • I'd suggest use the fully qualified class name as parameter for getMockBuilder(). And, did you extend the correct WebTestCase class, the Symfony\Bundle\FrameworkBundle\Test\WebTestCase? Commented Sep 29, 2017 at 11:15
  • Unfortunately this makes no difference...yes its the correct WebTestCase :) Commented Sep 29, 2017 at 11:25

1 Answer 1

1

Maybe? it's the only thing i see...

$service = $this->getMockBuilder(ApiTestManager::class)
        ->disableOriginalConstructor()
        ->setMethods(['getResponse'])
        ->getMock();
$service->expects($this->any())
        ->method('getResponse')
        ->will($this->returnValue(new Response()));
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it works, thank you...but I don't understand why :D Do you know why I can't chain the methods like I did before?
really don't understand why, as you can seegetMock() returning the result of generator, but i've always seen this way on documentation, examples and projects...

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.