[英]Mocking a custom class with Mockery in Laravel 4
使用Laravel 4.2,我在/app/libraries
有一個自定義類TestyClass
。
我正在嘗試使用Mockery和PHPUnit模擬該類,但我的Mock似乎沒有注冊。
當我運行測試時,我得到Mockery\\Exception\\InvalidCountException: Method testymethod() from Mockery_0_TestyClass should be called exactly 1 times but called 0 times.
我正在測試的Controller運行TestyClass::testymethod();
,並且testymethod()
內部的Log :: info正確運行。
在Laravel 4.2中注冊自定義類的模擬項時,我缺少什么?
$mock = Mockery::mock('TestyClass');
$mock->shouldReceive('testymethod')->once();
TestyClass:
class TestyClass {
public static function testymethod() {
Log::info('----=-=-=-=--=in heyhey!@!!=-=-=-=-=-=-=-12312312312312341');
return true;
}
}
這段代碼:
$mock = Mockery::mock('TestyClass');
創建一個擴展TestyClass
的新類,添加模擬等所需的行為,然后創建它的實例並返回它,因此$ mock是Mockery_0_TestyClass
的實例。
然后,您要告訴嘲笑您希望該實例接收到對testymethod
的調用,但實際上您是在對TestyClass
類方法進行靜態調用。 您可以通過嘲弄來做到這一點,但這並不是很好,我不建議您這樣做,您可能希望使用進程隔離來運行測試。
$mock = Mockery::mock('alias:TestyClass');
您在打電話給您的控制器嗎? 測試類方法和測試控制器有所不同。 如果要測試控制器,請嘗試使用$this->call
示例;
class TestyClassTest extends TestCase {
public function setUp()
{
$this->mock = $this->mock('TestyClass');
}
/* Move method to TestCase.php */
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
/* Move method to TestCase.php */
public function tearDown()
{
Mockery::close();
}
public function testIfTestyControllerRunsTestyMethodAndReturnsOk()
{
// Step 3. Arrange
// Last we arrange our test
$this->mock->shouldReceive('testymethod')->once();
// Step 2. Act
// Then we write how we the results will be asserted.
// The route should correspond with the controller executing the class method.
// Eg. TestyMethodController@test; return $this->class->testymethod()
**$this->call('GET', 'TestyController@test');**
// Step 1. Assert
// Start by writing the results we expect;
// If the controller issues no Exceptions we should get a response header status 200.
$this->assertResponseOk();
}
}
本質上,$ mock-> shouldReceive是在模擬對象上設置一個偵聽器,它正在等待方法運行-如果運行該方法,則一切正常,否則將收到InvalidCountException。
希望對您有幫助,祝您有美好的一天。
我遇到過類似的問題:班級未被認可。 嘗試使用__construct方法對其進行初始化。 那對我有用。 (在setUp方法中設置它無效)。
public function __construct()
{
$this->mock = Mockery::mock('TestyClass');
}
然后只需調用測試方法:
$this->mock->shouldReceive('testymethod')->once();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.