首页 > 解决方案 > 在phpunit测试中模拟非类函数

问题描述

我有一个 for-each 循环的原始 PHP 代码。我正在使用php 7.2PHPUnit 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 调用。

标签: phpphp-7phpunit

解决方案


您必须将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 输出缓冲文档,PHPUnit 可用断言


推荐阅读