php - 在phpunit测试中模拟非类函数
问题描述
我有一个 for-each 循环的原始 PHP 代码。我正在使用php 7.2
和PHPUnit 8
。
这里是文件名app.php
,代码如下: 这里我有另一个CalculatorAPI()
需要 API 调用的调用 - 也需要一个模型。
$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);
推荐阅读
- react-native - react-native-sqlite-storage windows createFromLocation 错误
- python - 用于具有阈值的多输出图像分类的拆分数据集
- c# - 从一个时区转换到另一个时区时,在本地计算机上找不到时区 id 'Russia TZ 8 Standard Time
- python - 带有初始网络的迁移学习模型的预处理
- html - requests:获取 Google Doc 或 Sheet 的最后修改时间?
- c# - 如何在 RS232 串口和本地笔记本电脑之间获取命令历史记录?
- reactjs - 自定义断点未显示在我的断点选项中
- huggingface-transformers - Transformer-base 或 Transformer-big 有多少个参数和 FLOP?如何计算?
- rdma - RDMA 读写数据放置/可见性语义
- c# - ThirdPersonMovement script Unity