且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-21 04:57:58

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

Depending on how your code is setup, you may be able to "mock" the function. If your code is using namespaces, you can take advantage of how PHP looks for the correct function to call.

如果将测试放在与代码相同的名称空间中,则可以用可以控制的其他功能替换帮助程序功能.

If you place your test in the same namespace as your code, you can replace the helper function with a different function that you can control.

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

You would want your class to like something like this:

namespace foo;

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

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

Then you could make the test like so:

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将在函数的直接名称空间中查找,如果找不到该名称,则会转到全局名称空间.因此,将测试放在与您的类相同的名称空间中,将允许您在单元测试中替换它.

This works provided that the helper function does not have its namespace specified in the call (ie /helperFunction). PHP will look in the immediate namespace for the function and if it isn't found will then go to the global namespace. So placing the test in same name space as your class will allow you to replace it in your unittest.

检查参数或更改返回值可能很棘手,但是您可以利用测试用例中的某些静态属性来检查内容.

Checking parameters or changing return values can be tricky but you can take advantage of some static properties in your testcase to check things.

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');
    }
}

如果在代码中未使用命名空间,则完全无法模拟该函数.您需要让您的测试代码使用实际功能,并检查类中的结果.

If you are not using namespacing in your code, you are not able to mock the function at all. You would need to let your test code use the actual function and check the results in your class.