我有一个for-each循环的原始PHP代码。我使用的是 php 7.2
和 PHPUnit 8
.
这里是文件名 app.php
代码如下。这里我有另一个调用 CalculatorAPI()
这需要API调用--也需要一个mockup。
$list = file_get_contents('input.txt');
$inputData = explode("\n", trim($list));
function main ( $inputData ) {
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], '"}');
// Class which needs a mock up because it requires API call
$calApi = new CalculatorAPI();
$result =$calApi->getFinalResult($currency);
echo $result;
print "\n";
}
}
main( $inputData );
注意:在 input.txt
我有 {"currency":"EUR"}...
来获取货币列表。
现在我需要为 PHPUnit test
* 这是测试文件
<?php
require_once __DIR__."/../app.php";
use PHPUnit\Framework\TestCase;
class AppTest extends TestCase
{
public function testApp() : void
{
$calAPI = $this->createStub(CalculatorAPI::class);
$calAPI->method('getFinalResult')
->willReturn(1);
$result = main($this->data, $calAPI);
$this->assertEquals(1, $result);
}
}
当我运行这个文件时,它就会执行这个文件。我如何编写代码 raw PHP
另外,我需要离线运行测试,虽然它需要一个API调用。
你必须包装你的 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);