簡體   English   中英

Symfony:使用 PHPSpec 測試時如何設置 session

[英]Symfony: How to set session when testing with PHPSpec

我目前正在嘗試使用 PHPSpec 測試我的 LocaleSubscriber(它處理我的應用程序的大部分多語言工作)。 到目前為止,我知道,我需要模擬一個請求。

我的代碼目前如下所示:

public function it_rediredts_to_en_when_nothing_is_parsed(RequestEvent $event, Session $session)
{
    $request = $event->getRequest();
    $request->setSession($session);
    $request->shouldBeCalled()->willReturn(Request::create('/en/cleaning-rotas'));
    $session->get('language')->shouldBeCalled()->willReturn('en');
    $this->onKernelRequest($event);
}

現在我收到此錯誤: Call to undefined method Prophecy\Prophecy\MethodProphecy::setSession() 但是,一旦我在沒有任何 session 東西的情況下對此進行測試,我就會收到錯誤消息exc:BadMethodCallException("Session has not been set.") ,這對我來說很有意義。 但我不知道如何在這種情況下設置 session,以便我可以繼續處理請求。

到現在為止,都是關於我要測試的這部分代碼。

public function onKernelRequest(RequestEvent $event)
{
    $request = $event->getRequest();

    //Specify Locale (set threw session/is null)
    $customLocale = $request->getSession()->get('language') ?: $this->defaultLocale;

有人可以給我任何提示嗎? 我是 PHPSpec 的新手,直到現在才使用例如 PHPUnit。

好吧,我做了一些研究,找到了一種對我有用的方法。 PHPSpec 與 PHPUnit 有很大不同。

public function it_redirects_to_en(RequestEvent $event, Session $session, Request $request)
{
    $request->getSchemeAndHttpHost()->willReturn('http://localhost');
    $request->getPathInfo()->willReturn('/');
    $request->getSession()->willReturn($session);

    $event->getRequest()->shouldBeCalled()->willReturn($request);
    $session->get('language')->shouldBeCalled()->willReturn('en');
    $this->onKernelRequest($event);

    [...]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM