HMR*_*HMR 4 phpunit doctrine mocking entitymanager symfony
在我的测试中,我正在尝试模拟实体管理器,因此它将返回一个不会连接到数据库但是返回假值的存储库:
在根据此文档的测试中:
$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();
//....
Run Code Online (Sandbox Code Playgroud)
在测试中,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"];
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中:
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;
}
Run Code Online (Sandbox Code Playgroud)
永远不会使用虚假存储库,因为在运行测试时回显没有出现.
直到创建模拟我认为它正在工作,但设置模拟可能是问题,$container->set('doctrine.orm.entity_manager',$mockManager);因为调用$this->getDoctrine()->getManager()时控制器获取实际的实体管理器而不是模拟实体.
嗯,每次我花很多时间试图解决问题; 在我决定发布问题之后,答案在另一个谷歌搜索中显示出来并尝试:
解决方案是:
$container->set('doctrine.orm.default_entity_manager', $mockManager);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2336 次 |
| 最近记录: |