PHPUnit存根连续调用

时间:2013-03-20 15:25:52

标签: php unit-testing mocking

我遇到了一个类的问题,它返回不可预测的值并且单元测试调用该函数的方法。所以我要改变方法的回报。

我无法模拟该方法,因为我无法创建实例。这是一个例子:

// Class called MyClass
public function doSomething(){
    $foo = new Foo();
    $bar = $foo->getSomethingUnpredictable();

    // Doing something with $bar and saves the result in $foobar.
    // The result is predictable if I know what $foo is.

    return $forbar;
}

// The test class
public function testDoSomething{
    $myClass = new MyClass();
    when("Foo::getSomethingUnpredictable()")->thenReturns("Foo");

    // Foo::testDoSomething is now predictable and I am able to create a assertEquals
    $this->assertEquals("fOO", $this->doSomething());
}

我可能会检查Foo :: testDoSomething在单元测试中返回什么,因此计算结果但是testDoSomething与doSomething的区别很小。我也无法检查其他值会发生什么 doSomething不能有任何参数,因为使用了varargs(所以我无法添加最佳参数)。

1 个答案:

答案 0 :(得分:0)

这就是硬连线依赖关系不好的原因,它的当前状态doSomething是不可测试的。你应该像那样重构MyClass

public function setFoo(Foo $foo)
{
    $this->foo = $foo;
}
public function getFoo()
{
    if ($this->foo === null) {
        $this->foo = new Foo();
    }
    return $this->foo;
}
public function doSomething(){
    $foo = $this->getFoo();
    $bar = $foo->getSomethingUnpredictable();

    // Doing something with $bar and saves the result in $foobar.
    // The result is predictable if I know what $foo is.

    return $forbar;
}

然后您将能够注入模拟的Foo实例:

$myClass->setFoo($mock);
$actualResult = $myClass->doSomething();

至于如何存根方法,它取决于你的测试框架。因为这个(when("Foo::getSomethingUnpredictable()")->thenReturns("Foo");)不是PHPUnit。

相关问题