【问题标题】:PHPUNIT Test - Expected Status 200 But Received 500PHPUNIT 测试 - 预期状态 200 但收到 500
【发布时间】:2019-03-20 08:55:53
【问题描述】:

当预期为 200 时,我不断获得状态 500。这些是文件:

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

提供ScriptVariables.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,
            ];
        }
    }
}

非常感谢任何帮助。

【问题讨论】:

  • 由于错误消息表明错误发生在 app.blade.php 中,请与我们分享此文件。
  • @TimSch:添加了 app.blade.php 的内容。谢谢
  • 好的,你的错误信息说你在 null 上调用 load()。我看不到任何负载调用。所以我会更深入地挖掘。这个 Ezbyz 课是你自己做的吗?我希望我们会在 ProvidesScriptVariables.php 文件的第 46 行找到 scriptVariables()。请也发布此内容。
  • @TimSch:添加了 ProvidesScriptVariables.php 的内容
  • 不知何故,在我删除并重建 docker 卷和图像之后,测试现在没有问题地通过了。但是,当我推送到 Gitlab 并再次执行测试时,它失败并出现相同的错误,即。预计 200,但收到 500

标签: laravel phpunit


【解决方案1】:

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

use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

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

        $response->assertStatus(200);
    }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      只需编辑你的类以返回 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);
          }
      }
      

      然后在你的命令中运行测试

      vendor/bin/phpunit

      【讨论】:

        【解决方案4】:

        请检查您的路线。检查您是否为基本路线提供了“名称”。

        例如: 在 routes/web.php 中,执行以下操作:

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

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

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

        让我知道它是否适合你。

        【讨论】:

          猜你喜欢
          • 2021-05-24
          • 2018-03-01
          • 2018-11-26
          • 1970-01-01
          • 2016-08-18
          • 2020-08-07
          • 1970-01-01
          • 2019-08-01
          • 1970-01-01
          相关资源
          最近更新 更多