我有从 HttpFoundation 请求对象返回值的类。我想为该课程编写测试,但我遇到了问题。那是我的课:
class RequestCollected
{
private $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function getUserAgent(): string
{
return $this->request->headers->get('User-Agent');
}
public function getUri(): string
{
return $this->request->request->get('uri');
}
}
那是我的测试:
public function testGetUserAgent()
{
$userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
$request = $this->prophesize(Request::class);
$request->headers = $this->prophesize(HeaderBag::class);
$request->headers->get('User-Agent')->willReturn($userAgent);
$collected = new RequestCollected($request->reveal());
$this->assertEquals($userAgent, $collected->getUserAgent());
}
public function testGetUri()
{
$uri = 'test';
$request = $this->prophesize(Request::class);
$request->request = $this->prophesize(ParameterBag::class);
$request->request->get('uri')->willReturn($uri);
$collected = new RequestCollected($request->reveal());
$this->assertEquals($uri, $collected->getUri());
}
两个测试的错误相同:错误:调用成员函数 willReturn() on null
有什么解决办法吗?或者另一种方法来测试什么正在使用请求对象?
问候