Rui*_*ira 7 php testing phpunit include phpstorm
我在phpunit测试中包含一个文件时遇到了一些麻烦.例如:当我在PhpStorm中执行以下代码时,我得到了预期的输出.
码:
class NifvalidationTest extends PHPUnit_Framework_TestCase
{
public function test_apiRequest()
{
$result = 1+1;
$this->assertEquals(2, $result);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Testing started at 16:58 ...
PHPUnit 5.2.12 by Sebastian Bergmann and contributors.
Time: 120 ms, Memory: 11.50Mb
OK (1 test, 1 assertion)
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
但是当我需要使用include从另一个类访问一个方法时,我得不到预期的输出.举个例子,当我执行以下代码时:
class NifvalidationTest extends PHPUnit_Framework_TestCase
{
public function test_apiRequest()
{
include('/../nifvalidation.php');
$result = 1+1;
$this->assertEquals(2, $result);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这个而不是预期的输出:
Testing started at 17:05 ...
PHPUnit 5.2.12 by Sebastian Bergmann and contributors.
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
关于包含为什么会破坏测试的任何想法?
注1:在上面的例子中我不需要包含文件,但我需要在另一个测试中.
注意2:文件'nifvalidation.php'的路径是正确的.
小智 6
我认为你的包含路径是错误的.你的结构可能有点像这样的
ParentDir
- > nifvalidation.php
- > testsFolder
- > NifvalidationTest.php
而不是
include('/../nifvalidation.php')
Run Code Online (Sandbox Code Playgroud)
使用
include(dirname(__FILE__)."/../nifvalidation.php");
Run Code Online (Sandbox Code Playgroud)
从命令行调用测试时,可以使用该bootstrap标志包含任何文件,定义常量,并加载所有变量,类等.
Run Code Online (Sandbox Code Playgroud)--bootstrap <file> A "bootstrap" PHP file that is run before the tests.
例如,创建一个autoload.php定义常量并包含文件的,然后可以从命令行调用它,如下所示:
phpunit --bootstrap autoload.php testsFolder/NifvalidationTest
Run Code Online (Sandbox Code Playgroud)
对于更自动化的方法,您还可以创建包含引导信息的phpunit.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="autoload.php">
<testsuites>
<testsuite name="Nifvalidation Test Suite">
<directory>./testsFolder</directory>
</testsuite>
</testsuites>
</phpunit>
Run Code Online (Sandbox Code Playgroud)
在这种特定情况下,根据您nifvalidation.php对脚本退出内容的注释,因为PS_VERSION未定义.如果您正在进行单独的单元测试,只需要定义一个虚拟常量,那么您可以定义它在测试环境中存在.然后你可以简单地引导你的nifvalidation.php文件.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="../nifvalidation.php">
<testsuites>
<testsuite name="Nifvalidation Test Suite">
<directory>./testsFolder</directory>
</testsuite>
</testsuites>
<php>
<const name="PS_VERSION" value="whatever you need here"/>
</php>
</phpunit>
Run Code Online (Sandbox Code Playgroud)