gpt4 book ai didi

laravel - 测试一个方法是否被调用

转载 作者:行者123 更新时间:2023-11-28 21:27:56 25 4
gpt4 key购买 nike

我正在尝试找出如何正确测试函数是否被调用。

此函数 busqueda 是在 Controller 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');
}

}

但是 assert 总是失败,我是不是用错了 mock?

错误信息:

PHPUnit 4.8.21 by Sebastian Bergmann and contributors.

....E

Time: 352 ms, Memory: 23.25Mb

There was 1 error:

1) ExampleTest::testBuscador Mockery\Exception\InvalidCountException: Method busqueda() from Mockery_0_App_Http_Controllers_AnuncioController should be called exactly 1 times but called 0 times.

/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! Tests: 5, Assertions: 27, Errors: 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 的任何实例都被模拟替换,但事实并非如此。您需要将使用的 Controller 实例替换为 $mock_buscador 模拟对象。

关于laravel - 测试一个方法是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34341787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com