laravel PHPUNIT测试-预期状态200,但收到500

qf9go6mv  于 2023-06-07  发布在  PHP
关注(0)|答案(6)|浏览(148)

我一直得到状态500,而预期是200。这些是文件:

ExampleTest.php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

此为返回结果

PHPUnit 7.4.0 by Sebastian Bergmann and contributors.

.F                                                                  2 / 2 (100%)

Time: 1.86 seconds, Memory: 20.00MB

There was 1 failure:

1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 500.
Failed asserting that false is true.

/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/var/www/html/tests/Feature/ExampleTest.php:19

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

这是Laravel日志文件

[2018-10-15 20:56:09] testing.ERROR: Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) {"exception":"[object] (ErrorException(code: 0): Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46, Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function load() on null at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46)

app.blade.php

@php
$config = array_merge(
    Ezybyz::scriptVariables(), [
        // Add key and value here if you want to added to initial state
    ]
)
@endphp

@extends('layouts.main')

@push('meta')
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<meta name="csrf-token" content="{{ csrf_token() }}">
{{-- Fix for chunk error in Webpack and Vue-Router --}}
<base href="/" />
@endpush

@push('favicon')
<link rel="shortcut icon" href="{{ asset('favicon.ico?v=2') }}" type="image/x-icon" />
@endpush

@push('css')
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
@endpush

@push('header_js')
{{--  EzyByz initial state provider --}}
<script>
  window.App = @json($config)
</script>
{{-- Add whitelisted routes for making API calls --}}
@routes
@endpush

@push('title')
<title>{{ config('app.name') }} </title>
@endpush

@section('content')
<div id="app" v-cloak>
    <app />
</div>
@endsection

@push('footer_js')
@if(config('echo.realtime'))
{{-- Load socket.io --}}
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js" defer></script>
@endif

<script src="{{ mix('js/manifest.js') }}" defer></script>
<script src="{{ mix('js/vendor.js') }}" defer></script>
<script src="{{ mix('js/app.js') }}" defer></script>
@endpush

提供脚本变量.php

<?php

namespace App\Ezybyz\Configuration;

use App\Ezybyz\Ezybyz;
use Illuminate\Support\Facades\Auth;
use App\Ezybyz\Contracts\InitialFrontendState;

trait ProvidesScriptVariables
{
    /**
     * Get the default JavaScript variables for Spark.
     *
     * @return array
     */
    public static function scriptVariables()
    {
        return [
            'csrfToken' => csrf_token(),
            'env' => config('app.env'),
            'api_endpoint' => config('ezybyz.app.api'),
            'sponsor' => self::getSponsor(),
        ];
    }

    protected static function getState()
    {
        return Ezybyz::call(InitialFrontendState::class . '@forUser', [Auth::user()]);
    }

    protected static function getSponsor()
    {
        if ($link = request()->referrallink) {
            $user = Ezybyz::user()->find($link->user_id);

            return [
                'user_id' => $user->id,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'profile' => $user->profile,
            ];
        }
        // We Will Return a Default Sponsor
        else {
            $user = Ezybyz::user()->first()->load('profile');

            return [
                'user_id' => $user->id,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'profile' => $user->profile,
            ];
        }
    }
}

任何帮助都是非常感谢的。

szqfcxe2

szqfcxe21#

尝试在测试类中使用RefreshDatabase trait:

use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}
jdzmm42g

jdzmm42g2#

$response = $this->get('/');之前添加$this->withoutExceptionHandling();以获取有关错误的详细信息。

lg40wkob

lg40wkob3#

此错误消息的一个可能原因是,您没有启用openssl php扩展。

jtjikinw

jtjikinw4#

只需编辑类以返回true

namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
    
class ExampleTest extends TestCase
{
    /**
    * A basic test example.
    *
    * @return void
    */
    public function testBasicTest()
    {
        $this->assertTrue(true);
    }
}

然后在命令中运行test
vendor/bin/phpunit

nmpmafwu

nmpmafwu5#

这个答案可能有点晚,但可能会帮助新来者。

检查您的XAMPP/WAMP服务器是否正在运行,并确保其正在运行。

因为500是一个内部服务器错误,它主要发生在你的服务器没有响应或没有正常运行时。
我希望这对你有帮助

klh5stk1

klh5stk16#

检查你的路线。检查是否已为基本路由提供了“name”。
例如:在routes/web.php中,执行以下操作:

Route::get('home','BlogController@home')->name('home');

现在转到测试用例并替换以下代码:

$response = $this->get('home');

告诉我你是否适合。

相关问题