Summer Sale! All accounts are 50% off this week.

omniware's avatar

PhpUnit and access to External URL

On my windows PC I have an instance of laravel 5.2 running and I have one named route in it called testroute.

I wrote a phpunit test cases

public function testBasicExample1() {
    $this->visit('testroute')->see('Something'); //Passes
}
public function testBasicExample2() {
    $this->visit('http://www.google.com')->see("I'm Feeling"); //Fail
}

in TestCase.php $baseUrl = 'http://localhost:8000';

and in .env APP_URL=http://localhost:8000

How do I access external URLs in laravel phpunit testcases?

I need this as I have a separate non-laravel api server and I need to access those and test responses in my laravel project.

Thanks

0 likes
7 replies
omniware's avatar

Looks like people are not using phpunit much :|, am I using the right tool for testing? Anyone please, there is something strange going on with the $base_url, APP_URL and the visit function parameters that I am not able to figure out.

WM-Laravel's avatar

You can try Codeception which is popular for unit, functional and acceptance testing. And yes they use PHPUnit.

eugenefvdm's avatar

I've stumbled upon this post because I also want to know, with PHPUnit and Laravel testing, is it possible to specify and external URL when testing? I'm specifically referring to the following commands:

$response = $this->getJson($uri)

$response = $this->postJson($uri)

I imagine it's not common practice because I guess you have to mock, it's just my current workflow often starts with a few tests and when I start and before I know the API I like to start in the /tests folder.

I tried external URLs in PHPUnit and Laravel testing, but I get this:

"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",

Please advise.

agrocenta's avatar

It's been a couple of years this was asked but I surprising got stuck on this today for hours. I eventually had to proxy the external call through a route. In my case I do not want to fake the HTTP call since the whole point of the test is to check if a user can actually login to the external URL.

 //  routes/web.php
Route::post('/proxy', function (Request $request) {
    return http_request($request->get('url'), $request->except('url'));
});
// tests/Feature/SignUpTest.php
public function test_that_just_signed_up_company_can_sign_in()
{
    $response = $this->withHeaders(Constant::HEADERS)
        ->postJson(
            '/proxy', [
                'url' => config('app.api_url').'user/login',
                'login' => "[email protected]",
                'password' => 'abc123456',
            ]);

    $response->assertJson(Constant::DEFAULT_OK_RESPONSE);
}

http_request() above is a simple helper function I wrote that makes HTTP calls with some custom headers and validations.

Please or to participate in this conversation.