小编Che*_*ker的帖子

使用phpunit模拟抽象类中的具体方法

有没有什么好方法可以使用PHPUnit在抽象类中模拟具体方法?

到目前为止我发现的是:

  • expect() - > will()使用抽象方法工作正常
  • 它不适用于具体方法.而是运行原始方法.
  • 使用mockbuilder并给setMethods()提供所有抽象方法和具体方法.但是,它要求您指定所有抽象方法,使测试变得脆弱且过于冗长.
  • MockBuilder :: getMockForAbstractClass()忽略setMethod().


以下是一些单元测试,例如以上几点:

abstract class AbstractClass {
    public function concreteMethod() {
        return $this->abstractMethod();
    }

    public abstract function abstractMethod();
}


class AbstractClassTest extends PHPUnit_Framework_TestCase {
    /**
     * This works for abstract methods.
     */
    public function testAbstractMethod() {
        $stub = $this->getMockForAbstractClass('AbstractClass');
        $stub->expects($this->any())
                ->method('abstractMethod')
                ->will($this->returnValue(2));

        $this->assertSame(2, $stub->concreteMethod()); // Succeeds
    }

    /**
     * Ideally, I would like this to work for concrete methods too.
     */
    public function testConcreteMethod() {
        $stub = $this->getMockForAbstractClass('AbstractClass');
        $stub->expects($this->any())
                ->method('concreteMethod')
                ->will($this->returnValue(2)); …
Run Code Online (Sandbox Code Playgroud)

php phpunit unit-testing mocking

15
推荐指数
2
解决办法
1万
查看次数

为什么我们必须将克隆分配给新变量?

我目前正在学习使用Propel ORM,我想重用一个critera用于两个稍微不同的查询:

$criteria = ArticleQuery::create()
        ->filterByIsPublished(true)
        ->orderByPublishFrom(Criteria::DESC)
        ->joinWith('Article.Author')
        ->keepQuery();

$this->news = $criteria
        ->filterByType('news')
        ->find();
$this->articles = $critera
        ->filterByType('article')
        ->find();
Run Code Online (Sandbox Code Playgroud)

但是,这不会按预期工作,因为现在对文章的查询将尝试查找类型为"新闻"和"文章"的条目,这当然是不可能的.

所以我们需要得到这个对象的克隆,对我来说似乎直观的是简单地在paranthesis中添加clone关键字:

$this->news = (clone $criteria)
        ->filterByType('news')
        ->find();
Run Code Online (Sandbox Code Playgroud)

Parse error: syntax error, unexpected T_OBJECT_OPERATOR

相反,我们必须先将它分配给变量才能使用它:

$clonedCritera = clone $criteria;
$this->news = $clonedCriteria
        ->filterByType('news')
        ->find();
Run Code Online (Sandbox Code Playgroud)

您与new运营商具有相同的行为.我看到推进开发者通过替换:
new ArticleQuery()->doOperations()with来规避这个限制ArticleQuery::create()->doOperations().

为什么PHP语言设计者选择这样做?如果你可以直接使用这些表达式的结果,它将使代码更流畅,在某些情况下,更容易阅读.

php propel fluent-interface fluent

5
推荐指数
1
解决办法
389
查看次数

标签 统计

php ×2

fluent ×1

fluent-interface ×1

mocking ×1

phpunit ×1

propel ×1

unit-testing ×1