Laravel phpUnit测试错误,在Test类中有多个函数

时间:2016-02-10 22:05:57

标签: unit-testing laravel

我的测试课很简单

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/');

    }

    // when I add this, I get an error
    public function testAnotherExample()
    {
        $this->visit('profile');

    }
}

当我只有“testBasicExample”方法时,测试运行正常。但是,只要我添加“testAnotherExample”,测试就会失败并显示以下错误消息。

Fatal error: Cannot redeclare formatBytes() (previously declared in C:\xampp\htdocs\laravellab\helpers\functions.php:3) in C:\xampp\htdocs\laravellab\helpers\functions.php on line 7

Fatal error: Uncaught exception 'Illuminate\Contracts\Container\BindingResolutionException' with message 'Target [Illuminate\Contracts\Debug\ExceptionHandler] is not instantiable.' in C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Container\Container.php:749
Stack trace:
#0 C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Container\Container.php(631): Illuminate\Container\Container->build('Illuminate\\Cont...', Array)
#1 C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(674): Illuminate\Container\Container->make('Illuminate\\Cont...', Array)
#2 C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(154): Illuminate\Foundation\Application->make('Illuminate\\Cont...')
#3 C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php(79): Illuminate\Foundation\Bootstrap\HandleExceptions->getExceptionHandler()
#4 C:\xampp\htdocs\laravellab\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 749

同样的测试如果我注释掉“testBasicExample”,那么另一个测试就可以了。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

上面的PHPUnit 5.3.2在Laravel 5中运行得很好。

您需要先卸载旧的phpunit

sudo apt-get purge phpunit
sudo apt-get purge --auto-remove phpunit

然后安装PHPUnit 5.6.1,如下所示

wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
sudo mv phpunit.phar /usr/local/bin/phpunit
phpunit --version

现在你可以运行 phpunit !!!

答案 1 :(得分:0)

来自@ceejayoz的回答是:

Fatal error: Cannot redeclare formatBytes() (previously declared in C:\xampp\htdocs\laravellab\helpers\functions.php:3) in C:\xampp\htdocs\laravellab\helpers\functions.php on line 7

是罪魁祸首。

然而,从include到include_once的解决方案灵丹妙药只是检查include是否只声明一次,这是在程序PHP中包含文件的经典方法。

我建议自动加载文件,而不是更改composer.json文件。只需在自动加载部分

中包含逻辑文件路径(来自composer.json文件的位置)
"autoload": {
    "files": ["helpers\functions.php"]

},

https://getcomposer.org/doc/04-schema.md#files