我有一个for-each循环的原始PHP代码。我正在使用php 7.2
和PHPUnit 8
。
这里是文件名app.php
,代码如下:
$list = file_get_contents('input.txt');
$inputData = explode("\n", trim($list));
foreach ($inputData as $row) {
if (empty($row)) break;
//explode row
$p = explode(",", $row);
// retrieve bin, amount and currency
$p2 = explode(':', $p[0]);
$currency = trim($p2[1], '"}');
echo $currency;
print "\n";
}
注意:在input.txt
中,我有{"currency":"EUR"}...
要获取货币列表。
现在我需要为PHPUnit test
写一些代码::这是测试文件
<?php
require_once __DIR__."/../app.php";
use PHPUnit\Framework\TestCase;
class AppTest extends TestCase
{
public function test() : void
{
$this->assertEquals(1, 1);
}
}
当我运行此命令时,它将执行文件。如何编写raw PHP
的代码?
您必须将foreach
代码包装到一个函数中,例如说myForeach
,以防止其在require_once __DIR__."/../app.php";
时间执行。
然后您必须从测试中运行myForeach
函数。在测试中,您必须捕获myForeach
函数的输出。捕获它之后,您必须将其与希望看到的函数成功生成的期望值进行比较。
然后您的AppTest::test()
可能如下所示:
$actual = myForeach();
$this->assertEquals('my expected foreach return value', $actual);
这仅适用于myForeach
显式返回值的情况(无论您是否有意地返回值)。现在,如果您希望myForeach
在控制台中输出,而不是显式返回某些值(如果您是TDD例如CLI实用程序,则可能是这种情况),您的测试应如下所示:
// Wrap your `myForeach` function into something special
// to catch its console output made with `print`
ob_start();
myForeach();
$actual = ob_get_clean();
// Now you have all your output from the function in $actual variable
// and you can assert with PHPUnit if it contains the expected string
$this->assertStringContainsString('my expected foreach return value', $actual);
某些链接:PHP输出缓冲docs,可用PHPUnit assertions