如何测试在类方法中是否调用了辅助函数?

时间:2017-10-05 13:32:10

标签: php unit-testing testing phpunit

假设我在PHPUnit中测试以下类:

class ExampleClass
{
    public function exampleMethod()
    {
        exampleHelperfunction('firstArg', 'secondArg');
    }
}

如何在exampleHelperFunction运行时使用参数'firstArg''secondArg'测试是否调用了exampleMethod

换句话说,我如何模拟非类方法的函数?

1 个答案:

答案 0 :(得分:0)

根据您的代码设置方式,您可能能够" mock"功能。如果您的代码使用名称空间,您可以利用PHP查找正确调用函数的方式。

https://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

如果将测试放在与代码相同的命名空间中,则可以使用可以控制的其他函数替换辅助函数。

你希望你的班级喜欢这样的东西:

namespace foo;

class SUT {
     public function methodToTest() {
         exampleHelperFunction();
     }
 }

然后你可以像这样进行测试:

namespace foo;

function helperFunction() {
    //Check parameters and things here.
}

class SUTTest extends PHPUnit_Framework_Testcase {
    public function testMethodToTest() {
        $sut = new SUT();
        $sut->methodToTest();
    }
}

如果辅助函数没有在调用中指定其命名空间(即/helperFunction),则可以使用此方法。 PHP将查找该函数的直接命名空间,如果找不到它将转到全局命名空间。因此,将测试放在与您的班级相同的名称空间中将允许您在您的单元测试中替换它。

检查参数或更改返回值可能很棘手但您可以利用测试用例中的一些静态属性来检查事物。

namespace foo;

function helperFunction($a1) {
    SUTTest::helperArgument = $a1;
    return SUTTest:helperReturnValue;
}

class SUTTest extends PHPUnit_Framework_Testcase {
    public static $helperArgument;
    public static $helperReturnValue;

    public function testMethodToTest() {
        self::helperReturnValue = 'bar';
        $sut = new SUT();
        $result = $sut->methodToTest('baz');

        $this->assertEquals(self::helperReturnValue, $result);
        $this->assertEquals(self::helperArgument, 'bar');
    }
}

如果您未在代码中使用命名空间,则根本无法模拟该功能。您需要让测试代码使用实际功能并检查您班级的结果。