【问题标题】:PHPUnit Stubbing consecutive callsPHPUnit 存根连续调用
【发布时间】:2013-03-20 15:25:51
【问题描述】:

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

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

// 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 不能有任何参数,因为使用了可变参数(所以我无法添加最佳参数)。

【问题讨论】:

    标签: php unit-testing mocking


    【解决方案1】:

    这就是硬连线依赖关系不好的原因,在其当前状态下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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2014-09-09
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多