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