控制器中的未定义变量我试图用laravel中的phpunit进行测试

时间:2013-10-11 02:01:16

标签: php unit-testing laravel phpunit

我正在尝试学习单元测试的基础知识,我正在使用phpunit和laravel

这是我的控制器

FatController.php

class FatController extends BaseController {

    public $result;

    public function __construct($result)
    {
        $this->result = $result;
    }

    public function getResult()
    {
        return $this->$result;
    }
}

和测试类

FatControllerTest.php

class FatControllerTest extends TestCase {

    /**
     * A basic functional test example.
     * @return void
     */

    public $test;

    public function setUp()
    {
        parent::setUp();
        $this->test = new FatController('100%');
    }

    public function testResult()
    {
        $result = $this->test->getResult();
        $this->assertTrue($result == '100%', 'message');
    }
}

据我所知,当测试运行时,它应该创建一个新的变量$ test,它等于FatController的一个新实例,其值为100%

然后运行$ test FatController方法getResult,它应该返回$ result,它已被构造函数定义为'100%'

当测试运行时,我得到了这个

PHP Warning:  Uncaught exception 'ErrorException' with message 'Undefined variable: result' in /Users/irish/Dropbox/www/youtube/app/controllers/FatController.php:15
Stack trace:
#0 /Users/irish/Dropbox/www/youtube/app/controllers/FatController.php(15): Illuminate\Exception\Handler->handleError(8, 'Undefined varia...', '/Users/irish/Dr...', 15, Array)
#1 /Users/irish/Dropbox/www/youtube/app/tests/FatControllerTest.php(22): FatController->getResult()
#2 [internal function]: FatControllerTest->testResult()
#3 /Users/irish/.composer/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php(983): ReflectionMethod->invokeArgs(Object(FatControllerTest), Array)
#4 /Users/irish/.composer/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php(838): PHPUnit_Framework_TestCase->runTest()
#5 /Users/irish/.composer/vendor/phpunit/phpunit/PHPUnit/Framework/TestResult.php(648): PHPUnit_Framework_TestCase->runBare()
#6 /Users/irish/.composer/vendor/phpunit/phpunit/PHPUnit/Framework/TestCase.php(783): PHPUnit_Framework_TestResult->run(Object(Fat in /Users/irish/Dropbox/www/youtube/app/controllers/FatController.php on line 15
PHP Fatal error:  Cannot access empty property in /Users/irish/Dropbox/www/youtube/app/controllers/FatController.php on line 15

所以我理解$ result没有被定义为任何东西,并且当getResult尝试返回它时导致错误但我不知道我做错了什么

1 个答案:

答案 0 :(得分:5)

看起来你有一个错字。 return $this->$result;应为return $this->result;