英文:
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('user1@email.com');
$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.
英文:
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('user1@email.com');
$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.
答案1
得分: 0
尝试创建一个TestUser实体并扩展它使用User实体。然后停用在属性id中设置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);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论