在 PHPUnit 中包含测试
Including test in PHPUnit
我开始使用 PHPUnit,在我的第一次测试中我不明白为什么我必须使用 require "app/Slug.php";
而不是 require "../app/Slug.php";
这是测试代码:
<?php
use PHPUnit\Framework\TestCase;
class SlugTest extends TestCase{
public function test_render(){
require "app/Slug.php";
$slug = new Slug("My First Test");
$this->assertEquals($slug->render(), "my-first-test");
}
}
我想我可以使用 require "../app/Slug.php";
让它工作。我什至在控制台中测试了路由,但代码仅适用于 require "app/Slug.php";
有人知道为什么吗?
是的,您需要要求 app/Slag.php 加载 class 或其中的代码并从测试文件访问它。
但你可以使用 composer 通过 psr-4 or files
自动加载你的 类
这是正确的行为,因为您 运行 从项目根目录进行测试。所以当前工作目录是项目的根文件夹。 require
将尝试包含使用当前目录作为基本路径的相对路径。
如果您使用 require "../app/Slug.php";
,那么您应该从 tests
文件夹中 运行 phpunit
。
像这样:
# that way it will work with "../app/Slug.php"
cd tests
./../vendor/bin/phpunit SlugTest.php --color
因此,基本路径不是文件所在的位置,而是您 运行 它的来源。
我开始使用 PHPUnit,在我的第一次测试中我不明白为什么我必须使用 require "app/Slug.php";
而不是 require "../app/Slug.php";
这是测试代码:
<?php
use PHPUnit\Framework\TestCase;
class SlugTest extends TestCase{
public function test_render(){
require "app/Slug.php";
$slug = new Slug("My First Test");
$this->assertEquals($slug->render(), "my-first-test");
}
}
我想我可以使用 require "../app/Slug.php";
让它工作。我什至在控制台中测试了路由,但代码仅适用于 require "app/Slug.php";
有人知道为什么吗?
是的,您需要要求 app/Slag.php 加载 class 或其中的代码并从测试文件访问它。 但你可以使用 composer 通过 psr-4 or files
自动加载你的 类这是正确的行为,因为您 运行 从项目根目录进行测试。所以当前工作目录是项目的根文件夹。 require
将尝试包含使用当前目录作为基本路径的相对路径。
如果您使用 require "../app/Slug.php";
,那么您应该从 tests
文件夹中 运行 phpunit
。
像这样:
# that way it will work with "../app/Slug.php"
cd tests
./../vendor/bin/phpunit SlugTest.php --color
因此,基本路径不是文件所在的位置,而是您 运行 它的来源。