如何使用在控制器中返回虚假存储库的mock entitymanager?

时间:2014-07-16 06:02:13

标签: symfony doctrine mocking phpunit entitymanager

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

根据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"];
  }
}

在控制器中:

  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()时获得实际的实体管理器而不是嘲笑一个。

2 个答案:

答案 0 :(得分:5)

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

解决方案是:

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

答案 1 :(得分:0)

$容器 - >设置( 'doctrine.orm.entity_manager',$ mockManager);