Doctrine2 Unittest mock up entity in relationship
I am trying to create unittest of a service class - class which has EntityManager injected and is responsible for loading and creating entities.
The problem is in ::create(arra开发者_如何学运维y) method for entities which creates entity and sets all required related entities. So I thought it would be advisable to use mock object for this, but when I use following code (also seen here: How to create a mock object of a doctrine entity?)
<?php
public function testCreate($email, $password)
{
$role = $this->getMock('Role');
$this->service->create(
array('email' => $email,
'password' => $password,
'role' => $role));
}
// service (simplified)
public function create(array $values)
{
$user = new User();
$user->setEmail($values['email'])
->setPassword($values['password'])
->setRole($values['role']);
$this->getDatabaseManager()->persist($user)->flush();
return $user;
}
?>
It triggers: A new entity was found through a relationship that was not configured to cascade persist operations
Using:
$this->service->getDatabaseManager()->persist($role);
in the test triggers: Class Mock_Role_c64eda12 is not a valid entity or mapped super class.
How can I either fix this or what better approach can I use? (don't know which one applies more here...if the whole 'service creates and persists entites' or whatever else is a bad idea please let me know)
You dont want to mock the Role here, you want to mock the EntityManager. If you don't want to mock the entity manager you are in a functional test, in this case you can also work with the real Role object.
精彩评论