作者:看非诚勿扰是修炼 | 来源:互联网 | 2023-01-17 12:19
我在控制器上执行PHPUnit,似乎无法嘲笑Request权限。
这是控制器:
use Illuminate\Http\Request;
public function insert(Request $request)
{
// ... some codes here
if ($request->has('username')) {
$userEmail = $request->get('username');
} else if ($request->has('email')) {
$userEmail = $request->get('email');
}
// ... some codes here
}
然后在单元测试中,
public function testIndex()
{
// ... some codes here
$requestParams = [
'username' => 'test',
'email' => 'test@test.com'
];
$request = $this->getMockBuilder('Illuminate\Http\Request')
->disableOriginalConstructor()
->setMethods(['getMethod', 'retrieveItem', 'getRealMethod', 'all', 'getInputSource', 'get', 'has'])
->getMock();
$request->expects($this->any())
->method('get')
->willReturn($requestParams);
$request->expects($this->any())
->method('has')
->willReturn($requestParams);
$request->expects($this->any())
->method('all')
->willReturn($requestParams);
// ... some codes here
}
这里的问题是,无论何时我var_dump($request->has('username');
总是返回$requestParams
整个数组中的值。我期望它应该返回,true
因为用户名键存在于数组中。
然后,当我删除上的用户名密钥时$requestParams
,它应该返回false,因为它不包含username
数组中的密钥
1> 小智..:
模拟请求不是理想的选择,但有时您还是想这样做:
protected function createRequest(
$method,
$content,
$uri = '/test',
$server = ['CONTENT_TYPE' => 'application/json'],
$parameters = [],
$COOKIEs = [],
$files = []
) {
$request = new \Illuminate\Http\Request;
return $request->createFromBase(
\Symfony\Component\HttpFoundation\Request::create(
$uri,
$method,
$parameters,
$COOKIEs,
$files,
$server,
$content
)
);
}