Summer Sale! All accounts are 50% off this week.

kenprogrammer's avatar

PHPUnit: Cannot instatiate class in setUp method

See code snippette below:

<?php
    require 'vendor/autoload.php';

    use PHPUnit\Framework\TestCase;

    use Loan\LoanCalculator;

    final class LoanCalculatorTest extends TestCase
    {
        private $calculator;
 
        protected function setUp(): void
        {
            $this->calculator = new LoanCalculator();
        }

        /**
         * Test interest amount can be calculated correctly
         *
         * @dataProvider loanDataProvider
         */
        public function 										 
         test_interest_amount_can_be_calculated_correctly($interest_amount,$principle,$rate,$time)
        {
            //Verify interest amount can be calculated correctly
            $this->assertEquals($interest_amount,$calculator->calculateInterestAmount($principle,$rate,$time));
        }

        public function loanDataProvider()
        {
            return [
                'calculating interest amount'=>[690.0,10000,2.3,3]
            ];
        }

        protected function tearDown(): void
        {
            $this->calculator = NULL;
        }
    }
?>

When I run the test am getting the error below:

There was 1 error:

1) LoanCalculatorTest::test_interest_amount_can_be_calculated_correctly with data set "calculating interest amount" (690.0, 10000, 2.3, 3)
Undefined variable: calculator

Why is the calculator variable UNDIFINED and the class is being instatiated in setUp method?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

It is an instance variable but you are using it as a local variable in the test; use $this->calculator instead:

$this->assertEquals(
    $interest_amount,
    $this->calculator->calculateInterestAmount($principle,$rate,$time)
);
1 like

Please or to participate in this conversation.