Search code examples
sessionfunctional-testingsymfony5

Symfony5: prepare content of session for Functional Test


Background

I try to create a functional test (for existing code - I know about TDD, but anyway the code exist already).

This is a "booking"-process using multiple steps (each seperate controller-function). The data is passed from one step to the other by storing the temporarily data into the SESSION (inside a CART-Object).

Question

For the test of step 3, I need to prepare the CART (at least one PRODUCT-Object and a PERSON-Object inside) and store it into the session, so that the controller-function can use it.

  • I can get the SESSION, that contains already the CART with one PRODUCT
  • I can add a PERSON-Object to the CART-Object

BUT: How do I store the CART-Object back into the SESSION?

Thanks for help!!!

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

    // ...

}

Solution

  • Just add this:

       $session->save():