symfony – 如何使用mock entitymanager在控制器中返回虚拟存储
发布时间:2020-12-13 17:30:59 所属栏目:PHP教程 来源:网络整理
导读:在我的测试中,我正在尝试模拟实体管理器,因此它将返回一个不会连接到数据库但是返回假值的存储库: 在根据this documentation的测试中: $session = new Session(new MockArraySessionStorage()); $mockManager = $this -getMockBuilder('DoctrineCommonP
在我的测试中,我正在尝试模拟实体管理器,因此它将返回一个不会连接到数据库但是返回假值的存储库:
在根据this documentation的测试中: $session = new Session(new MockArraySessionStorage()); $mockManager = $this ->getMockBuilder('DoctrineCommonPersistenceObjectManager') ->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(); //.... 在测试中,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"]; } } 在控制器中: 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; } 永远不会使用虚假存储库,因为在运行测试时回显没有出现. 直到创建模拟,我认为它的工作正常,但设置模拟可能是问题$container-> set(‘doctrine.orm.entity_manager’,$mockManager);作为控制器,当调用$this-> getDoctrine() – > getManager()获取实际的实体管理器而不是模拟实体. 解决方法
嗯,每次我花很多时间试图解决问题;在我决定发布问题之后,答案在另一个谷歌搜索中显示出来并尝试:
解决方案是: $container->set('doctrine.orm.default_entity_manager',$mockManager); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |