Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHPUnit存根连续调用_Php_Unit Testing_Mocking - Fatal编程技术网

PHPUnit存根连续调用

PHPUnit存根连续调用,php,unit-testing,mocking,Php,Unit Testing,Mocking,我遇到了一个类的问题,它返回不可预测的值,并对调用该函数的方法进行单元测试。所以我要改变一个方法的返回 我无法模拟该方法,因为我无法创建实例。以下是一个例子: // Class called MyClass public function doSomething(){ $foo = new Foo(); $bar = $foo->getSomethingUnpredictable(); // Doing something with $bar and saves

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

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

// 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(因此我无法添加最佳参数)。

这就是硬连线依赖项不好的原因,在其当前状态下
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::getsomethingunprodictable()”)->thenReturns(“Foo”);
)不是PHPUnit