0

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(‘[email protected]'), $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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Okay i will try this approach. Thank you! But would you be knowing to answer my problem in terms of mocking the database?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.