R
R
rst6302021-11-02 12:22:12
PHPUnit
rst630, 2021-11-02 12:22:12

How to override class method when testing laravel phpunit?

There is a ServiceApi.php class - a guzzle client with default options is created in its constructor: it also has a method:
$this->client = new Client($options);

public function fetch()
{
return $this->client->get('http://......')->getBody()->getContents();
}


And there is another class, say ServiceUser.php - it has a method that uses the ServiceApi class:
public function fetchFromApi()
{
return (new ServiceApi())->fetch();
}


in the test, I want that when calling (new ServiceUser())->fetchFromApi() - the guzzle client does not access the real api, and I explicitly defined its entire response in the test in advance.

I tried to mock the ServiceApi class, but it only works inside the test, when the call comes from the ServiceUser, then the real fetch() method is called. Is it

even possible to do this?
Or am I trying to test something that I should not test in this way, or is the architecture initially not suitable for such testing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2021-11-11
@dostrog

you can, in conjunction with Laravel, you can use https://laravel.com/docs/8.x/http-client#testing
or mock your class (like this for me)

$this->mock(RestApi::class, function (MockInterface $mock) use ($user) {
            $mock->shouldReceive('login')
                ->with($user->phone, $user->pass)
                ->andReturn([
                    'result' => ApiStatus::OK,
                ]);
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question