2013-06-25 37 views
5

我開始與Silex一起工作,它非常棒。嘗試對我的課進行適當的單元測試時會出現問題。具體:( 在下面的線封我解釋一下,看看我的問題,如果有的話,你知道如何解決它。 請,不注重語法,但測試問題本身。使用PHPUnit進行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類的$ app ['foo_bar']之後的「()」中。 當試圖執行測試時,我得到一個「PHP致命錯誤:函數名稱必須是...中的字符串」錯誤。 我明白我不能以這種方式單元測試這個類,但是我沒有看到正確的方法來完成它。

我怎麼能測試這個語句(因爲最後唯一複雜的語句是$ this-> bar = $ app'foo_bar';)?

+0

也許github會給你一些啓發:https://github.com/fabpot/Silex/tree/master/tests/Silex/Tests – qrazi

+0

我已經試過,但找不到一個很好的例子:( – ThisIsErico

回答

3

好吧,我想我設法正確地測試這個閉包!最後的測試看起來像這樣:

<?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); 
    } 
} 

而不是返回模擬,我返回一個閉包,返回模擬。通過這種方式,我仍然在使用實際的模擬工具時沒有收到錯誤信息。

誰能告訴我,如果這是一個正確的做法?