【问题标题】:How to properly use atLeastOnce method in Codeception\Util\Stub?如何在 Codeception\Util\Stub 中正确使用 atLeastOnce 方法?
【发布时间】:2016-03-16 05:57:12
【问题描述】:

我正在使用 codeception 来测试我的 PHP 应用程序,并且有一种我不知道如何使用的方法。它被称为Stub::atLeastOnce(),就像Codeception's documentation of the Stub class 所说:

"检查一个方法是否至少被调用过一次。如果调用次数为0,则会在verify中抛出异常。"

但是当我尝试使用它时,无论我是否评论对User::getName() 的调用,测试都通过了。

我的用户类如下所示:

<?php

class User {
  public function getName() {
    return 'pepito';
  }

  public function someMethod() {

  }
}  

而我的测试方法是这样的:

public function testStubUsage() {
    // all methods that the stub impersonates must be, at least, defined
    $user = Stub::make('User', array('getName' => Stub::atLeastOnce(function() { return 'Davert'; }), 'someMethod' => Stub::atLeastOnce('User::getName')));
    $user->getName();
}

那么,如果从未调用过 User::getname(),那么该函数的用途是什么?

【问题讨论】:

    标签: php stub codeception


    【解决方案1】:

    文档不正确,您必须将$this 作为Stub::make() 的第三个参数传递才能正常工作:

    public function testStubUsage() {
        $user = Stub::make('User', array('getName' => Stub::atLeastOnce(function() { return 'Davert';}), 'someMethod' => function() {}), $this); // <- Here
        $user->getName();
    }
    

    【讨论】:

    • 另外,如果您使用不扩展 \PHPUnit_Framework_TestCase 的 Cest 格式(Stub::doGenerateMock(),由 Stub::make() 调用,检查如果第三个参数是\PHPUnit_Framework_TestCase 的实例,则在使用它之前)。请参阅stackoverflow.com/questions/26140295/…,其中 OP 对此进行了快速而肮脏的修复。
    猜你喜欢
    • 2014-11-26
    • 2020-10-06
    • 1970-01-01
    • 2019-02-21
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    相关资源
    最近更新 更多