测试方法是否被调用

时间:2015-12-17 18:31:18

标签: laravel testing phpunit mockery

我试图弄清楚如何对某个函数是否被调用进行正确的测试。

此功能 busqueda 是在控制器 AnuncioController 中定义的,所以我希望在用户点击发布到 anuncios / busqueda的搜索按钮时调用它

就我而言,这可能是用模拟做的。这就是我尝试过的:

use \App\Http\Controllers;
class ExampleTest extends TestCase
{

   public function testBuscador()
   {
    $mock_buscador = Mockery::mock(\App\Http\Controllers\AnuncioController::class);
    $mock_buscador->shouldReceive('busqueda')->once()->andReturn(null);
    $this->visit('/')->submitForm('Buscar')->seePageIs('anuncios/busqueda');
   }

}

但断言总是失败,我错误地使用了模拟吗?

错误消息:

  

Sebastian Bergmann和贡献者的PHPUnit 4.8.21。

     

... E

     

时间:352毫秒,内存:23.25Mb

     

有1个错误:

     

1)ExampleTest :: testBuscador Mockery \ Exception \ InvalidCountException:   方法busqueda()来自   应该调用Mockery_0_App_Http_Controllers_AnuncioController   恰好1次,但被称为0次。

     

/var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery/CountValidator/Exact.php:37   /var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery/Expectation.php:271   /var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery/ExpectationDirector.php:120   /var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery/Container.php:297   /var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery/Container.php:282   /var/www/html/anuncios.com/vendor/mockery/mockery/library/Mockery.php:142   /var/www/html/anuncios.com/tests/ExampleTest.php:19

     

FAILURES!测试:5,断言:27,错误:1。

Routes.php片段:

Route::post('anuncios/busqueda', [
    'as' => 'anuncios/busqueda',
    'uses' => 'AnuncioController@busqueda',
]);

AnuncioController.php片段:

public function busqueda(Request $request)
{...}

1 个答案:

答案 0 :(得分:1)

您创建模拟对象$mock_buscador而不实际使用它。看起来您希望将App\Http\Controllers\AnuncioController的任何实例替换为模拟,但事实并非如此。您需要将使用过的控制器实例替换为$mock_buscador模拟对象。