D
D
driverx182021-07-07 16:32:39
PHP
driverx18, 2021-07-07 16:32:39

How to lock the results of a method so that it doesn't make an API call?

there is a situation, there is a method that I want to test, there is a method:

public function getPaidShops() : array
    {
        $categories = $this->getCategories();

        $data = $this->getLicense($categories);

        return $this->format($data);
    }


everything would be fine, but here the getLicense method is called which makes an API call. This is what happens inside:
private function getLicense(array $categories)
    {
        return app(APIService::class)->getLicenses($categories);
    }


I would like this method not to go into the apishka (all the more it cannot call it from tests, because an error is generated that the session is not set), but I would like to specifically block this method. How can I do that?
Alternatively, you can rewrite the code so that the APIService is passed to the constructor in the class under test (and not created directly in the method), and in unit tests, pass the mock of this class to the constructor with the data that will be thrown into getLicenses from the data provider.
But I would not want to rewrite the code and replace in all places of the project, maybe there are some other solutions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-07-07
@rpsv

Make the getLicense method protected and for the test inherit from the main class and replace the getLicense method.
Then you won't have to rewrite anything at all.

public function testCase()
{
    $mockObject = $this->createMock(NeedClass::class);
    // чем это принципиально отличается от мока с точки зрения теста - непонятно
    $mockObject = new class extends NeedClass {
        protected function getLicense(array $categories)
        {
            return 'need license';
        }
    };

    $this->assertEqual($mockObject->getPaidShops(), 'actual value');
}

Alternatively, you can rewrite the code so that APIService is passed to the class being tested in the constructor (and not created directly in the method), and in unit tests, pass the mock of this class to the constructor with the data that will be thrown into getLicenses from the service provider

Well, in general, this is how it should be done, DI is all business :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question