symfony 和 phpunit 中带有请求对象的测试方法

Test method with request object in symfony and phpunit

我有来自 HttpFoundation 请求对象的 class 和 returns 值。我想为 class 编写测试,但我遇到了问题。 那是我的class:

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());
    }

两个测试的错误相同: 错误:在 null

上调用成员函数 willReturn()

有什么解决办法吗?或者另一种测试正在使用请求对象的东西的方法?

问候

你不需要使用预言或模拟对象来测试这个简单的class

public function testGetUserAgent()
{
    $userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0';
    $request = new Request();
    $request->headers = new HeaderBag(['User-Agent' => $userAgent]);
    $collected = new RequestCollected($request);
    $this->assertEquals($userAgent, $collected->getUserAgent());
}

您唯一需要的是检查您的 class 是否正在获取有效请求的信息,有时事情比我们想象的要简单:)