我试图弄清楚如何对某个函数是否被调用进行正确的测试。
此功能 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)
{...}
答案 0 :(得分:1)
您创建模拟对象$mock_buscador
而不实际使用它。看起来您希望将App\Http\Controllers\AnuncioController
的任何实例替换为模拟,但事实并非如此。您需要将使用过的控制器实例替换为$mock_buscador
模拟对象。