phuedx/pinkerton

使用 UOPZ 模拟 Jasmine 的 `spyOn` 函数。

v2.0.1 2014-11-28 16:48 UTC

This package is not auto-updated.

Last update: 2024-09-14 13:18:06 UTC


README

因此,您正在调用某个遗留函数。也许它甚至是一个 内部 函数——它不是 microtime 吗?您正在编写测试并希望断言其调用方式或模拟其行为。

您应该使用 Pinkerton

Pinkerton 允许您使用 @krakjoe 的 UOPZ 扩展 包装 JasminespyOn 函数来监视或模拟函数和方法的行为。

监视

function legacy_function($parameter)
{
    // Do all of the things.
}

$spy = spyOn('legacy_function')->andCallThrough();
$legacyParameter = 1;
legacy_function($legacyParameter);
var_dump($spy->mostRecentCall); // [‘args’ => [1]]

模拟

$spy = spyOn('legacy_function')->andCallFake(function() {
    return false;
});
var_dump(legacy_function($legacyParameter)); // false

测试

因此,您正在编写一个测试用例,该用例接受一个 callable 参数。嗯,您可以将 Pinkerton 监视器作为参数传递,使用监视器调用该方法,然后对调用方式做出一些断言。

class FooTest extends PHPUnit_Framework_TestCase
{
    public function test_bar_should_call_the_callable()
    {
        $spy = createSpy();
        $foo = new Foo();
        $foo->bar($spy);
        $this->assertEquals($spy->callCount, 1);
    }
}

API

/**
 * Spies on the function or method.
 *
 * The function or method is replaced with a handler that will invoke a spy
 * that wraps the original function or method.
 *
 * Note that when spying on a method, the method is replaced with the handler
 * for all instances of the class.
 *
 * @param callable $function
 * @return \Phuedx\Pinkerton\Spy The spy that will be invoked instead of the
 *  function or method
 */
function spyOn($function) {}

/**
 * Stops spying on the function or method.
 *
 * The original function or method is restored but the spy is unaffected.
 *
 * @param callable $function
 * @throws \InvalidArgumentException When the function or method isn't being
 *  spied on
 */
function stopSpyingOn($function) {}

/**
 * Creates a spy that doesn't wrap a function or method.
 *
 * @return \Phuedx\Pinkerton\Spy
 */
function createSpy() {}

许可证

Pinkerton 使用 MIT 许可证,版权所有 © 2012-2014 Sam Smith。有关完整的版权和许可证信息,请参阅 LICENSE 文件。