How to test if a helper function was called inside a class method?

你。 提交于 2019-12-11 17:30:06

问题


Say I am testing the following class in PHPUnit:

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

How can I test if exampleHelperFunction was called with the arguments 'firstArg' and 'secondArg' when exampleMethod was run?

In other words, how can I mock functions that are not class methods?


回答1:


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.

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

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

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.



来源:https://stackoverflow.com/questions/46586957/how-to-test-if-a-helper-function-was-called-inside-a-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!