Symfony5:为功能测试准备会话内容

Symfony5: prepare content of session for Functional Test

背景

我尝试创建一个功能测试(针对现有代码 - 我知道 TDD,但无论如何代码已经存在)。

这是一个使用多个步骤(每个单独的控制器功能)的“预订”过程。通过将临时数据存储到 SESSION(在 CART 对象内),数据从一个步骤传递到另一个步骤。

问题

为了第3步的测试,我需要准备好CART(里面至少有一个PRODUCT-Object和一个PERSON-Object),存入session中,让controller-function可以使用。

但是:如何将 CART 对象存储回 SESSION?

感谢帮助!!!

class BookingControllerTest extends WebTestCase {

   // ...

    public function testStep3_CustomerDataValidation() {
        // create the CLIENT
        $this->client  = static::createClient();

        // get random PRODUCT and add to CART
        $product = $this->getRandomProduct(1)->first();
        $this->addProductToCart($product);      // this is working! (creation of Session with cart-object inside)

        // add PERSON to CART-Object and store back into SESSION
        $session  = $this->client->getContainer()->get('session');
        $cart     = $session->get('cart');
        $person   = $this->personFactory->createPerson('Peter', 'Parker');
        $cart->setPerson($person);
        
        // --------------------------------------------------------
        // HOW TO STORE THE CART-OBJECT BACK INTO THE SESSION??????
        // --------------------------------------------------------

        // make the REQUEST (step 3) and assert it
        $this->client->request('GET', "/customer/validation");
        $this->assertResponseStatusCodeSame(200);

    }


    private function addCourseToCart(Product $product): void {

        // make REQUEST
        $urlAddItem = "/add/{$product->getSlug()}";
        $this->client->request('GET', $urlAddItem);

        // assert RESPONSE
        $this->assertResponseStatusCodeSame(302);
        $this->assertTrue($this->client->getResponse()->isRedirect('/show/cart'));
    }

    // ...

}

只需添加:

   $session->save():