Mark
Mark

Reputation: 3197

Undefined variable in controller I am trying to test with phpunit in laravel

I am trying to learn the basics of unit testing and I am using phpunit and laravel

Here is my controller

FatController.php

class FatController extends BaseController {

    public $result;

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

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

and the test class

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');
    }
}

As far as I know when the test runs it should create a new variable $test which is equal to a new instance of FatController with a value of 100%

It then runs $test FatController Method getResult which should return $result which has been defined by the constructor as '100%'

When the test runs however I get this

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

So I understand that $result is not being defined as anything and that is causing an error when getResult tries to return it but I don't know what I have done wrong

Upvotes: 1

Views: 4080

Answers (1)

George Brighton
George Brighton

Reputation: 5151

It looks like you have a typo. return $this->$result; should be return $this->result;.

Upvotes: 5

Related Questions