【问题标题】:Testing in Silex (mock closures) using PHPUnit使用 PHPUnit 在 Silex(模拟闭包)中进行测试
【发布时间】:2013-06-25 19:46:13
【问题描述】:

我开始使用 Silex,感觉非常棒。尝试对我的课程进行适当的单元测试时会出现问题。具体来说,闭包:( 在以下几行中,我解释了我的问题,看看你们中是否有人知道如何解决它。 请不要关注语法,而要关注测试问题本身。

我有这样的提供者:

<?php

namespace Foo\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;

use Foo\Bar;

class BarProvider implements ServiceProviderInterface {

    public function register( Application $app ) {
        $app[ 'foo_bar' ] = $app->protect( function() use ( $app ) {
            return new Bar( $app );
        } );
    }

    public function boot( Application $app ) {}
}

然后我需要获取一个 foo_bar 元素的实例:

<?php

namespace Foo;

use Silex\Application;

class Clazz {
    protected $bar;

    public function __construct( Application $app ) {
        $this->bar = $app[ 'foo_bar' ]();
    }
}

这很好用。问题是我正在使用 TDD(和 PHPUnit)进行开发,我无法正确测试 Clazz 类。

<?php

namespace Foo\Test;

use PHPUnit_Framework_TestCase;

use Silex\Application;

use Foo\Bar;
use Foo\Clazz;

class ClazzTest extends PHPUnit_Framework_TestCase {

    public function testConstruct() {
        $mock_bar = $this->getMock( 'Foo\Bar' );

        $mock_app = $this->getMock( 'Silex\Application' );
        $mock_app
            ->expects( $this->once() )
            ->method( 'offsetGet' )
            ->with( 'foo_bar' )
            ->will( $this->returnValue( $mock_bar ) );

        new Class( $mock_app );
    }
}

这里的问题在于 Clazz 类中 $a​​pp[ 'foo_bar' ] 之后的“()”。 尝试执行测试时,我收到“PHP 致命错误:函数名称必须是...中的字符串”错误。 我知道我无法以这种方式对课程进行单元测试,但我没有看到正确的方法。

我如何测试这个语句(因为最后唯一的复杂语句是 $this->bar = $app 'foo_bar' ; )?

【问题讨论】:

标签: testing phpunit closures silex


【解决方案1】:

好的,我想我成功地测试了这个闭包!最终测试如下所示:

<?php

namespace Foo\Test;

use PHPUnit_Framework_TestCase;

use Silex\Application;

use Foo\Bar;
use Foo\Clazz;

class ClazzTest extends PHPUnit_Framework_TestCase {

    public function testConstruct() {
        $mock_bar = $this->getMock( 'Foo\Bar' );

        $mock_app = $this->getMock( 'Silex\Application' );
        $mock_app
            ->expects( $this->once() )
            ->method( 'offsetGet' )
            ->with( 'foo_bar' )
            ->will( $this->returnValue( function() use( $mock_bar ) { return $mock_bar; } ) );

        new Class( $mock_app );
    }
}

我没有返回模拟,而是返回一个返回模拟的闭包。这样我在仍然使用实际模拟时不会收到错误。

谁能告诉我这是否正确?

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 2017-08-16
    • 2011-10-10
    • 1970-01-01
    • 2016-06-04
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多