Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当存在其他参数时,模拟模型绑定将失败_Php_Laravel_Phpunit - Fatal编程技术网

Php 当存在其他参数时,模拟模型绑定将失败

Php 当存在其他参数时,模拟模型绑定将失败,php,laravel,phpunit,Php,Laravel,Phpunit,我正在使用Laravel的browserkit测试来测试我应用程序中的路线 路线定义为: web.php Route::post("myroute/{mymodel}", "MyController@viewMyModel"); 路由服务提供者 Route::model("mymodel", MyModel::class); 霉菌控制者 public function viewMyModel(Request $req, MyModel $myModel, $parameter) {

我正在使用Laravel的browserkit测试来测试我应用程序中的路线

路线定义为:

web.php

Route::post("myroute/{mymodel}", "MyController@viewMyModel");
路由服务提供者

Route::model("mymodel", MyModel::class); 
霉菌控制者

public function viewMyModel(Request $req, MyModel $myModel, $parameter) {
   //Does things
}
我现在需要测试MyModel的一个特定实例的行为

我的测试用例是:

public function testDoesThingsWithoutFailing() {
    $this->withoutMiddleware();
    $this->app->instance(MyModel::class, $this->getMockBuilder(MyModel::class)->getMock());        
    $urlToVisit = url()->action("ReportsController@saveComponentAs", [
        "mymodel" => 123, "parameter" => "p"
    ]);
    $this->call("POST", $urlToVisit);
    $this->assertResponseStatus(200);
}
当我这样做时,它会失败,因为“mymodel”作为控制器的3个参数传递,因为第二个参数是从容器中注入的,即当我执行
func_get_args
inside
viewMyModel
I get:

array:4 [
0 => Illuminate\Http\Request ...
1 => Mock_MyModel_6639c39c {...}
2 => "123"
3 => "p"
]
这是错误的(但是预期的),因为参数2现在被注入,而不是被路由绑定替换

然而当我尝试

$urlToVisit = url()->action("ReportsController@saveComponentAs", [
     "parameter" => "p"
]);
我明白了

UrlGenerationException:缺少[Route:]所需的参数

在理想情况下,我不需要使用
$this->without middleware()
,但我现在需要这样做,因为如果我不这样做,模型似乎会正常解析,而不是通过容器解析

我做错什么了吗?我错过了一些明显的东西吗?

这个答案让我找到了正确的解决方案

问题是:

我禁用了禁用路由绑定的中间件,这是故意的,因为我认为我需要它。然而,这使得框架注入模型,而不是用模型替换参数。在所有注入模型之后,该参数最终被添加到请求中

解决方案:

继续使用模型绑定,但模拟绑定结果。以下是有效的方法:

public function testDoesThingsWithoutFailing() {
    // Need the middleware to run
    $this->app->get('router')->bind(MyModel::class, function () { 
         return $this->getMockBuilder(MyModel::class)->getMock(); 
    }); 
    $urlToVisit = url()->action("ReportsController@saveComponentAs", [
        "mymodel" => 123, "parameter" => "p"
    ]);
    $this->call("POST", $urlToVisit);
    $this->assertResponseStatus(200); //Works as expected
}

路由需要一个您未提供的
mymodel
参数,如果将路由参数更改为
参数
@LeoinstanceofKelmendi该怎么办。我确实在测试的第一个实例中提供了它,但随后我通过了123,作为
$parameter
第四个参数,其值为
“p”
。。基本上,它被移动了一个位置(我在分享测试用例时注意到了这一点),我怀疑这可能是一个框架错误!不过我会在下班后调查的!看起来很有趣的虫子。@LeoinstanceofKelmendi我想我发现我在这里做错了什么。这就是答案。我通过禁用中间件和使用容器绑定来禁用模型绑定,但这是不正确的。我需要保留和模拟模型绑定。我一开始工作就回答