【发布时间】:2017-08-25 15:54:35
【问题描述】:
我正在尝试了解 PHP 命名空间并使用 PHPUnit 进行测试。
当我在 Windows 的命令行中运行 phpunit test.php 时,这些来自 Codewars 的测试通过:
<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;
class myTests extends TestCase {
public function testExamples() {
$this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
$this->assertEquals(pair_sum([1,2,3,1],3),1);
$this->assertEquals(pair_sum([1,3,2,2],4),2);
$this->assertEquals(pair_sum([1],4),false);
$this->assertEquals(pair_sum([2,3,10,-5],5),2);
}
}
但是,当我注释掉 use PHPUnit\Framework\TestCase; 时,我得到 Class 'TestCase' not found,这是有道理的,因为没有引用所需的类/函数。
但让我感到困惑的是,这里有很多关于命名空间的答案声称 use 关键字不能替代 include/require 并且仍然需要包含/自动加载类(?)。
我在这里没有使用任何自动加载 - 只是一个 solution.php 文件和 test.php 文件中的上述测试。
有人可以解释一下我在这里缺少什么吗?没有任何明确的 PHPunit 功能,测试如何工作?
我应该提到我已经通过 Composer 全局安装了 PHPUnit。
【问题讨论】:
-
没有
Use vs Include in PHP,如果你想以正确的方式使用use,你必须使用autoloader来加载类。 -
而
use用于在当前脚本中获取速记。这与包含无关。你也可以class myTests extends \PHPUnit\Framework\TestCase { -
您通过
phpunit运行该文件,它已经加载了所有相关的PHPUnit 文件。use没有加载文件,phpunit加载了。 -
Can someone please explain what I'm missing here?@deceze 一针见血。通过phpunit运行的脚本不像php那样工作。
标签: php namespaces include phpunit