Symfony2 PHPUnit模拟数据库问题 [英] Symfony2 PHPUnit Mocking the database issue

查看:151
本文介绍了Symfony2 PHPUnit模拟数据库问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图理解嘲笑数据库一段时间,并没有完全理解。我是一个Symfony2项目。我有一个控制器,我需要测试。因此我使用PHPUnit测试。除了嘲弄数据库部分,我设法了解其他一切。控制器的作用是认证用户。为了这个使用数据库,Ive没有线索,我如何可以相应地测试和配置它。这是我试过的,



控制器:

  class LoginController extends Controller 
{
public function indexAction(Request $ request)
{
$ em = $ this-> getDoctrine() - > getManager( );
$ usersRepo = new UsersRepository($ em);

$ form = $ this-> createForm(new LoginForm());

$ form-> handleRequest($ request);

if($ form-> isValid()){

$ request_data = $ request-> get($ form-> getName());

$ useremail = $ request_data ['useremail'];
$ password = $ request_data ['password'];

$ user = $ usersRepo-> userAuthenticate($ useremail,$ password);

if($ user)
{
$ session = $ this-> getRequest() - > getSession();
$ session-> set('user',$ user);
return $ this-> redirect($ this-> generateUrl('homepage'));
}
else
{
$ this-> get('session') - > getFlashBag() - > set('notice','Login Failed' ;
}
}

return $ this-> render('TestBundle:Default:login.html.twig',array('form'=> $ form-> ; CreateView的()));
}

存储库是UsersRepository,Entity是Users。有了这些细节ive writtnen一个测试控制器。

  class LoginControllerTest扩展WebTestCase {
public function testlogoutActionValidSessionExist(){

$ employee = $ this-> getMock('\Test\DABundle\Entity\Users');
$ employee-> expects($ this-> once())
- > method('userAuthenticate')
- > with($ this-> hello@hotmail.com'),$ this-> equalTo('testworld'));;

//现在,模拟存储库,以便返回员工的模拟
$ employeeRepository = $ this-> getMockBuilder('\Doctrine\ORM\ UsersRepository)
- > disableOriginalConstructor()
- > getMock();
$ employeeRepository-> expects($ this-> once())
- > method('find')
- >将($ this-> returnValue雇员));

//最后,模拟EntityManager返回仓库的模拟器
$ entityManager = $ this-> getMockBuilder('\Doctrine\Common\Persistence\ObjectManager' )
- > disableOriginalConstructor()
- > getMock();
$ entityManager-> expects($ this-> once())
- >方法('getRepository')
- >将($ this-> returnValue employeeRepository));

$ client = static :: createClient();
$ client-> request(GET,/ user / login /);

$ this-> assertEquals(200,$ client-> getResponse() - > getStatusCode());
}
}

所以在这个测试控制器中,但试图明白让这个工作。请查看ive完成错误或建议有助于使其正常工作。谢谢你提前

解决方案

我不认为你需要真正的模拟数据库,而是生成一个临时一个用于运行测试。



要创建临时数据库,请将symfony配置为使用SQLite。然后将一些灯具加载到新的数据库中,并根据这些灯具对控制器执行测试。



框架后来处理数据库的删除。



我使用以下软件包来协助自动装载工具。



https://github.com/liip/LiipFunctionalTestBundle



在config_test.yml中设置与sqlite的连接。 / p>

  doctrine:
dbal:
default_connection:默认
连接:
默认值:
驱动程序:pdo_sqlite
路径:%kernel.cache_dir%/ test.db
字符集:UTF8


I have been trying to understand "Mocking a database" for some time and did not completely understand. What I have is a Symfony2 project. I have a controller and I need to test it. Therefore im using PHPUnit testing. I managed to understand everything else except for mocking the database part. What the controller does is it authenticates a user. For this ive used the database and Ive no clue as to how I can test and configure it accordingly. Here’s what I have tried,

Controller:

class LoginController extends Controller
{
    public function indexAction(Request $request)
    {     
        $em = $this->getDoctrine()->getManager();
        $usersRepo = new UsersRepository($em);

            $form = $this->createForm(new LoginForm());

            $form->handleRequest($request);

            if ($form->isValid()) {

                $request_data = $request->get($form->getName());

                $useremail= $request_data['useremail'];            
                $password = $request_data['password'];

                $user = $usersRepo->userAuthenticate($useremail, $password);

                if($user)
                {                                      
                    $session = $this->getRequest()->getSession();  
                    $session->set('user', $user);
                    return $this->redirect($this->generateUrl('homepage'));             
                }
                else
                {                   
                    $this->get('session')->getFlashBag()->set('notice',’Login Failed’);                      
                }
            }

        return $this->render('TestBundle:Default:login.html.twig', array('form' => $form->createView()));
    }

The repository is "UsersRepository" and Entity is "Users". With these details ive writtnen a test controller.

class LoginControllerTest extends WebTestCase {
     public function testlogoutActionValidSessionExist() {

        $employee = $this->getMock('\Test\DABundle\Entity\Users');
        $employee->expects($this->once())
            ->method('userAuthenticate')
            ->with($this->equalTo(‘hello@hotmail.com'), $this->equalTo('testworld'));;

        // Now, mock the repository so it returns the mock of the employee
        $employeeRepository = $this->getMockBuilder('\Doctrine\ORM\ UsersRepository)
            ->disableOriginalConstructor()
            ->getMock();
        $employeeRepository->expects($this->once())
            ->method('find')
            ->will($this->returnValue($employee));

        // Last, mock the EntityManager to return the mock of the repository
        $entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
            ->disableOriginalConstructor()
            ->getMock();
        $entityManager->expects($this->once())
            ->method('getRepository')
            ->will($this->returnValue($employeeRepository));

        $client = static::createClient();               
        $client->request("GET", "/user/login/");

        $this->assertEquals(200 , $client->getResponse()->getStatusCode());
    }   
}

So in this test controller ive put code from the web but trying to understand to get this working. Please see where ive done wrong or a suggestion would help to get this working. Thank you in advance

解决方案

I don't think you need to actually 'mock' the database, but rather, generate a temporary one to run your tests against.

To create a temporary database, configure symfony to use SQLite. Then load in some fixtures into the new database and perform tests on the controllers against those fixtures.

The framework handles the deletion of the database afterwards.

I use the following bundle to assist with autoloading fixtures.

https://github.com/liip/LiipFunctionalTestBundle

In config_test.yml set up a connection to sqlite.

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:     pdo_sqlite
                path:       %kernel.cache_dir%/test.db
                charset:    UTF8

这篇关于Symfony2 PHPUnit模拟数据库问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆