Search code examples
unit-testingsymfonyphpunit

Symfony5 create a user for testing


I have a PurchaceFactory and one of its parameter is a User entity object.

I would like to create a user:

class PurchaceFactoryTest extends TestCase
{
    public function testCreate()
    {
        $user = new User();

        $user->setEmail('[email protected]');
        $user->setPassword('password');
        $user->setRoles(["ROLE_USER", "ROLE_BUY"]);

        $jsonEncoder = new JsonEncoder();

        $artworkData = [
            "ID"        => 129884,
            "title"     => "Starry Night and the Astronauts",
            "author"    => "Alma Thomas",
            "thumbnail" => [
                "lqip"     => "data:image/gif;base64,somebase64data",
                "width"    => 800,
                "height"   => 600,
                "alt_text" => "Al text"
            ]
        ];

        $purchaceFactory = new PurchaceFactory($jsonEncoder);
        $purchace = $purchaceFactory->create($user, $artworkData);
        //assertions
        //...
    }
}

The problem is, that I can not set the id of the user, since there is no setId for the entity when I made the bin/console make:user.

The purchaseFactory use that property of $user.

How could I simulate a User object with id?

I do not want to modify the UserEntity and add setId because id should be immutable.


Solution

  • Try creating a TestUser entity and extending it with the User entity. Then deactivate the strategy for setting the id in the property id.

    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Table(name="user")
     */
    class TestUser extend User
    {
        /**
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="NONE")
         * @ORM\Column(type="integer")
         */
        private $id;
    
        public function setId(int $id): void
        {
            $this->id = $id;
        }
    }
    
    $user = new TestUser();
    $user->setId(1000);