0

我有从 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

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

问候

4

1 回答 1

1

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

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

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

于 2017-05-05T03:35:15.850 回答