Как выполнить тестовый цикл в PHPUnit? - PullRequest
0 голосов
/ 03 декабря 2018

У меня есть класс обслуживания и тест для этого, следуйте ниже:

Класс

class MyCustomService
{
    public function job()
    {
       while($this->getResponseFromThirdPartyApi()->data) {
            // do some stuff...
       }    
       return ...
    }

    protected function getResponseFromThirdPartyApi()
    {
        // Here do some curl and return stdClass
        // data attribute is populated only on first curl request
    }
}

Проверка метода насмешки getResponseFromThirdPartyApi

class MyCustomServiceTest
{
    public function testJobImportingData()
    {
        $myCustomServiceMock = $this->getMockBuilder('MyCustomService')
        ->setMethods(array('getResponseFromThirdPartyApi'))
        ->getMock();

        $myCustomServiceMock->expects($this->any())
            ->method('getResponseFromThirdPartyApi')
            ->willReturn($this->getResponseWithData());

        $jobResult = $myCustomServiceMock->job();

        // here some assertions on $jobResult
    }

    protected function getResponseWithData()
    {
        $response = new \stdClass;
        $response->data = ['foo', 'bar'];

        return $response;
    }
}

Как я могу изменить возвращение getResponseWithData после первого вызова MyCustomService в цикле while?

Я попытался создать пользовательский флаг на MyCustomServiceTest и проверить getResponseWithData, но не удалось, как только смоделированный объект не выполняется.не вызывать метод getResponseWithData снова в MyCustomServiceTest.

В любом направлении?

1 Ответ

0 голосов
/ 04 декабря 2018

Как предложил Нико Хаазе выше, путь заключается в использовании обратного вызова.

После некоторого исследования я добился передачи ссылки на фиктивный объект методу mocked и проверки флага, это приводит к:

class MyCustomServiceTest
{
    public function testJobImportingData()
    {
        $myCustomServiceMock = $this->getMockBuilder('MyCustomService')
        ->setMethods(array('getResponseFromThirdPartyApi'))
        ->getMock();

        $myCustomServiceMock->expects($this->any())
            ->method('getResponseFromThirdPartyApi')
            ->will($this->returnCallback(
                function () use ($myCustomServiceMock) {
                    return $this->getResponseWithData($myCustomServiceMock)
                }
            ));

        $jobResult = $myCustomServiceMock->job();

        // here some assertions on $jobResult
    }

    protected function getResponseWithData(&$myCustomServiceMock)
    {
        $response = new \stdClass;

        if (isset($myCustomServiceMock->imported)) {
            $response->data = false;
            return $response;
        }

        $myCustomServiceMock->imported = true;

        $response = new \stdClass;
        $response->data = ['foo', 'bar'];

        return $response;
    }
}

Тогда цикл while будет вызываться только один раз, и мы сможем выполнить тест без цикла навсегда.

...