在Laravel中为测试添加子目录;连接无法解决

时间:2016-02-15 20:14:29

标签: php laravel-5 namespaces phpunit

我试图在我的/ tests /目录中添加一些结构,目前文件结构如下:

  • /测试
    • /型号
      • UserTest.php
    • ExampleTest.php
    • TestCase.php

UserTest和ExampleTest都是从TestCase扩展而来的。运行Exampletest工作正常(将用户添加到数据库),而UserTest失败并出现以下错误:

  

致命错误:在第3340行的[...] \ Illuminate \ Datab ase \ Eloquent \ Model.php中调用null上的成员函数connection()

这意味着此函数接收 null 或没有参数(model.php:3338-3342):

public static function resolveConnection($connection = null)
{
    return static::$resolver->connection($connection);
}

我无法弄清楚我的两个测试用例中有什么不同。

TestCase.php:

<?php
namespace Tests;

use Illuminate\Foundation\Testing\TestCase as baseTestCase;

class TestCase extends baseTestCase
{
    /**
     * The base URL to use while testing the application.
     *
     * @var string
     */
    protected $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__ . '/../bootstrap/app.php';

        $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();

        return $app;
    }
}

ExampleTest.php:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
use App\User;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        User::create([
            "name" => 'test'
        ]);

        $this->visit('/')
             ->see('Laravel 5');
    }
}

型号/ UserTest.php:

<?php

namespace Tests\Models;

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
use Faker\Factory;
use App\User;

class UserTest extends TestCase
{
    use DatabaseTransactions;

    protected $user;

    protected $password;

    protected $customPassword;

    protected $testString;
    /**
     * Construct.
     *
     * @return void
     */

    public function __construct()
    {
        $faker = Factory::create();

        $this->password = $faker->password;
        $this->customPassword = $faker->password;

        $this->user = User::create([
            "name" => $faker->name,
            "email" => $faker->email,
            "password" => Hash::shouldReceive($this->password),
        ]);

    }

    public function testExample()
    {
        $this->assertTrue(true);
    }
}

任何人都知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

我想这种情况正在发生,因为正在扩展&#34; TestCase&#34;来自Models / UserTest,它正在寻找&#34; TestCase&#34;在Models文件夹中,尝试提供该类的完整路径。

类似的东西:

class UserTest extends {yourNameSpace(ifAny)}\TestCase