mercredi 12 février 2020

Testing Mocking API call in Laravel

On the store method in the controller, I have a method that reaches out to the GitHub API to check if the submitted repository exists. This all works in the browser. I'm trying to create a test to mock the API to where I'm not making a real call.

However, in my test, it's hitting the API and not mocking resulting in a failing test.

How would I mock the GitHub API response in my test?

Controller store method (snippet of the API call):

...validation...

    try {
        $ghRepo = \GrahamCampbell\GitHub\Facades\GitHub::repo()->show(Str::before($request->repository, '/'), Str::after($request->repository, '/'));
    } catch (Exception $error) {
        return redirect()->back()->withErrors([
            'repository' => $error->getMessage(),
        ]);
    }

... store ... return view

Test:

public function test_it_can_create_repository_monitor()
    {
        $github = Mockery::mock(\Github\Api\Repo::class)
            ->shouldReceive('show')
            ->andReturn(['id' => 1, 'name' => 'dundermifflin/dwight-schrute-beet-farm-tips']);

        app()->instance(\Github\Api\Repo::class, $github);
        $response = $this->post(route('repository.create'),[
            'repository'    => 'dundermifflin/dwight-schrute-beet-farm-tips',
            'lock_location' => 'composer.lock',
        ])->assertOk();
    }

\Github\Api\Repo (if needed):

    public function show($username, $repository)
    {
        return $this->get('/repos/'.rawurlencode($username).'/'.rawurlencode($repository));
    }

Aucun commentaire:

Enregistrer un commentaire