如何在php单元测试中包含原始php

问题描述 投票:0回答:1

我有一个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调用,但我仍需要离线运行测试。

php phpunit php-7 phpunit-testing
1个回答
0
投票

您必须将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

© www.soinside.com 2019 - 2024. All rights reserved.