为什么抛出异常“未定义变量”?

时间:2021-02-02 19:48:50

标签: php phpunit

我有两个 php 文件。第一个 funcTest.php 包含一个函数,第二个 <?php function func(int $a, int $b, $data) { echo "$a, $b, $data"; return $a + $b; } 用于测试函数。
第一:

<?php
    require_once "PHPUnit/Autoload.php";
    use PHPUnit\Framework\TestCase;
    
    $data = "Some data";

    var_dump($data);
    
    final class funcTest extends PHPUnit_Framework_TestCase {
        public function testFunc() {
            require "func.php";
            $this->assertEquals(3, func(1, 2, $data));
        }
    }

第二:

details.stream().filter(detail-> detail.getItem()==item && detail.getName()==name && ...)

问题是当我在 cmd 中使用 phpunit 运行测试时,出现以下错误:

<块引用>

有 1 个错误:

  1. funcTest::testFunc 未定义变量:数据

C:\xampp\htdocs\someproject\funcTest.php:12

附言我在 SO 和其他论坛上发现了类似的问题,但没有一个对我有帮助。所以请不要关闭或关闭我的问题。

1 个答案:

答案 0 :(得分:-1)

正如其他人提到的,阅读变量作用域很好

$data = "Some data";

var_dump($data);

final class funcTest extends PHPUnit_Framework_TestCase {
    public function testFunc($data) // <---- You need to pass the $data variable into the method
    
    {
        require "func.php";
        $this->assertEquals(3, func(1, 2, $data));
    }
} 

// instantiate and call the method
$test = new funcTest;
$test->testFunc($data); //<--- Pass in the $data variable when calling the method