How to use mock entitymanager that returns fake repository in controller?
doctrine, entitymanager, mocking, phpunit, symfony
Solution
Hmm, every time I spend a lot of time trying to figure stuff out; right after I descide to post a question the answer shows itself in yet another google search and trying that:
Solution was:
$container->set('doctrine.orm.default_entity_manager', $mockManager);
Problem
In my test I'm trying to mock the entity manager so it'll return a repository that will not connect to the database but instead return a fake value: In the test according to this documentation: ``` $session = new Session(new MockArraySessionStorage()); $mockManager = $this ->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager') ->disableOriginalConstructor() ->getMock(); $mockManager->expects($this->any()) ->method('getRepository') ->will($this->returnValue(new userRepo())); $client = static::createClient(); $container = $client->getContainer(); $container->set('session', $session); $container->set('doctrine.orm.entity_manager',$mockManager); $client->request('POST', '/secured/login' ,array('userName'=>'username','password'=>'password' ,'rememberMe'=>'on')); $response = $client->getResponse(); //.... ``` In test, the userRepo: ``` class userRepo { public function isValidUser($userName, $password) { echo "this is isvaliduser"; return $this->getFullUserById(22); } public function getFullUserById($id){ echo "this is getfulluserbyid"; return ["name"=>"someName"]; } } ``` In the controller: ``` public function loginAction(Request $request) { $userRepo = $this->getDoctrine()->getManager() ->getRepository('mytestBundle:User'); $user=$userRepo->isValidUser($userName,$password); $response = new Response(); //... other code using session and whatnot $response->headers->set("Content-Type", 'application/json'); $response->setContent(json_encode($user)); return $response; } ``` The fake repository is never used as the echo doesn't show up when I run the test. Up until creating the mock I think it's working as it should but setting the mock may be the problem `$container->set('doctrine.orm.entity_manager',$mockManager);` as the controller when calling `$this->getDoctrine()->getManager()` gets the actual entity manager and not the mock one.