PHPUnit Test Confirms Registration Test Response Does Not Work and Error Occurs

Asked 1 years ago, Updated 1 years ago, 66 views

I am doing multi-posting, thank you for your cooperation.
https://teratail.com/questions/c842khs7083hca

I am creating apps with laravel and vue.js in the following environments.

  • MacOS
  • PHP 7.4.1
  • Lavel 6.20.26
  • PHPUnit 9.5.16

I don't know why RegisterApiTest.php doesn't go through when I test with PHPunit.

RegisterApiTest.php

<?php

namespace Tests\Feature;

use App\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class RegisterApiTest extensions TestCase
{
    use RefreshDatabase;

    /**
     * @test
     */
    public function should_Create and return a new user()
    {
        $data=[
            'name' = > 'user',
            'email' = > '[email protected]',
            'password' = > 'test1234',
            'password_confirmation' = > 'test1234',
        ];
(Comment function is disabled in postscript 2)
// dd($data);
        // Define a route for membership registration to routes/api.php
        // Route::post('/register', 'Auth\RegisterController@register') ->name('register');
        // Due to the influence of the controller, here is the register method in the @register→RegistersUsers trace.
        //  →Requires @registered→Write registered.This sends $data as registration data
        // Override the contents of the registered method in the RegisterController
        // send $data
(Comment function is disabled in postscript 2)
// dd($response);
        $response=$this->json('POST', route('register'), $data);


        $user=User::first();
(First test, this is line 37 of the editor.)
        $this->assertEquals($data['name'], $user->name);
(top omitted in 2nd test)
      // $this->assertEquals($data['name'], $user->name);

        $response
(This is line 40 of the editor for the second test.)
            - >assertStatus (201)
            ->assertJson(['name'=>$user->name]);
    }
}

Now that I've tried the test, I've found that the terminal.

First Test

root@bf0269c31cee:/var/www/html#./vendor/bin/phpunit tests/Feature/RegisterApiTest.php   
PHPUnit 9.5.16 by Sebastian Bergmann and contributors.

E 1/1 (100%)

Time: 00:01.960, Memory: 22.00 MB

There was 1 error:

1) Tests\Feature\RegisterApiTest::should_Create and return a new user
ErrorException—Trying to get property 'name' of non-object

/var/www/html/tests/Feature/RegisterApiTest.php:37

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

From here on line 37 of RegisterApiTest.php, I first thought that the name property was from (null?).

Next, I deleted the 37th line in question with the comment function.

Second Test

: /var/www/html#./vendor/bin/phpunit tests/Feature/RegisterApiTest.php 
PHPUnit 9.5.16 by Sebastian Bergmann and contributors.

F1/1 (100%)

Time: 00:03.398, Memory: 22.00 MB

There was 1 failure:

1) Tests\Feature\RegisterApiTest::should_Create and return a new user
Expected status code 201 but received 405.
Failed asserting that false is true.

/var/www/html/vendor/larvel/framework/src/Illuminate/Foundation/Testing/TestResponse.php: 186
/var/www/html/tests/Feature/RegisterApiTest.php: 40

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

I decided that this might cause an error because the response was not working well, so I went to see the routing and methods.

I'm making some routing changes for the API.

App/Providers/RouteServiceProvider.php is as follows:

protected function mapApiRoutes()
{
    Route::prefix('api')
//  Change to 'api' → 'web'
         ->middleware ('web') 
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

Routing for api is written to routes/api.php (not routes/web.php)

routes/api.php

<?php

use Illuminate\Http\Request;

// membership registration
Route::post('/register', 'Auth\RegisterController@register') ->name('register');

The methods are described in src/app/Http/Controllers/auth/RegisterController.php:

 code
protected function registered(Request$request,$user)
    {
        return$user;
    }

I don't know where I overlooked it.Thank you for your cooperation🙇♂️

Add


in laravel 6.0 $response=$this->json('POST', route('register'), $data);
I wondered if the writing style was strange, but in the 6 series documentation,

https://readouble.com/laravel/6.x/ja/http-tests.html

I think there is no problem here because of the following.

public function testBasicExample()
    {
        $response=$this->json('POST', '/user', ['name'=>'Sally']);

        $response
            - >assertStatus (201)
            - >assertExactJson([
                'created' = > true,
            ]);
    }

PHPUnit.xml

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="DB_CONNECTION" value="sqlite_testing"/>
    <server name="BCRYPT_ROUNDS" value="4"/>
    <server name="CACHE_DRIVER" value="array"/>
    <server name="DB_CONNECTION" value="sqlite"/>
    <server name="DB_DATABASE" value=":memory:"/>
    <server name="MAIL_DRIVER" value="array"/>
    <server name="QUEUE_CONNECTION" value="sync"/>
    <server name="SESSION_DRIVER" value="array"/>
  </php>

config/database.php

'connections'=>[
// Add
        'sqlite_testing' = > [
        'driver' = > 'sqlite',
        'database' = >': memory:',
        'prefix' = >',
        ],

Note 2
I looked it up using dd(), but sometimes the comments are too long, so I'd like to include excerpts of the important parts 🙇♂️ I'd like to write the location of dd() and its contents in the test code above in an easy-to-understand way.

dd($data); for

root@bf0269c31cee:/var/www/html#./vendor/bin/phpunit tests/Feature/RegisterApiTest.php
PHPUnit 9.5.16 by Sebastian Bergmann and contributors.

array:4 [
  "name" = > "user"
  "email" = > "[email protected]"
  "password" = > "test1234"
  "password_confirmation" = > "test1234"
]
root@bf0269c31cee:/var/www/html#


  dd($response); for

luminate\Foundation\Testing\TestResponse^{#1169
  +baseResponse —Illuminate\Http\JsonResponse^{#1209
    # data: "
      {\n
          "message": "The POST method is not supported for this route.Supported methods: GET, HEAD."\n
          "exception": "Symphony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",\n
          "file": "/var/www/html/vendor/larvel/framework/src/Illuminate/Routing/RouteCollection.php",\n
          "line"—256,\n
          "trace": [\n
              {\n
                  


    """
    # version: "1.0"
    # statusCode —405
    # statusText: "Method Not Allowed"
    # charset: null
    + original: array:5 [
      "message" = > "The POST method is not supported for this route. Supported methods: GET, HEAD."
      "Exception" = > "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException"
      "file"=>"/var/www/html/vendor/larvel/framework/src/Illuminate/Routing/RouteCollection.php"
      "line" = > 256
      "trace" = > array: 32 [
      


 + exception —Symphony\Component\HttpKernel\Exception\MethodNotAllowedHttpException^{#1185
      -statusCode—405
      -headers:array:1[
        "Allow" = > "GET, HEAD"
      ]
      # message: "The POST method is not supported for this route. Supported methods: GET, HEAD."
      # code : 0
      #file: "./vendor/larvel/framework/src/Illuminate/Routing/RouteCollection.php"
      # line —256
      trace: {


   ./vendor/larvel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:442 {…}
        ./tests/Feature/RegisterApiTest.php:34 {
          Tests\Feature\RegisterApiTest ->should_Create and return a new user()^
          › //dd($data);
          › $response=$this->json('POST', route('register'), $data);
          › 
          arguments: {
            $method: "POST"
            $uri: "http://localhost/127.0.0.1/api/register"
            $data:array:4[…4]
          }
        }


   }
  }
  # streamedContent: null
}
root@bf0269c31cee:/var/www/html# 

php laravel vue.js phpunit

2022-09-29 21:52

2 Answers

The helper function route() generates a URL.
https://readouble.com/laravel/6.x/ja/helpers.html#method-route

$response=$this->json('POST', route('register'), $data);

How about changing the second argument of the json method to 'api/register'?


2022-09-29 21:52

Self-resolved.

I noticed that $uri: "http://localhost/127.0.0.1/api/register" in postscript 2 and changed the part where 127.0.0.1 was originally written as follows.

before change:

REDIS_HOST=127.0.0.1
APP_URL = 127.0.0.1

after modification:

 REDIS_HOST=db (connected to docker's mysql)
APP_URL=

That's why either 127.0.0.1 caused url to go crazy and didn't go through.Thank you very much🙇♂️


2022-09-29 21:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.