gpt4 book ai didi

symfony - 如何使用在 Controller 中返回假存储库的模拟实体管理器?

转载 作者:行者123 更新时间:2023-12-05 00:25:20 25 4
gpt4 key购买 nike

在我的测试中,我试图模拟实体管理器,因此它将返回一个不会连接到数据库而是返回一个假值的存储库:

在按照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();
//....

在测试中,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"];
}
}

在 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;
}

永远不会使用假存储库,因为在我运行测试时没有出现回声。

在创建模拟之前,我认为它可以正常工作,但设置模拟可能是问题 $container->set('doctrine.orm.entity_manager',$mockManager);作为调用 $this->getDoctrine()->getManager() 时的 Controller 获取实际的实体管理器而不是模拟的。

最佳答案

嗯,每次我花很多时间试图弄清楚事情;在我决定发布一个问题之后,答案在另一个谷歌搜索中显示出来并尝试:

解决方案是:

  $container->set('doctrine.orm.default_entity_manager', $mockManager);

关于symfony - 如何使用在 Controller 中返回假存储库的模拟实体管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com