我试图弄清楚如何对是否正在调用函数进行适当的测试。

这个功能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
  
  失败!测试:5,断言:27,错误:1。


Routes.php片段:

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


AnuncioController.php片段:

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

最佳答案

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

07-25 23:48