如何在symfony3

时间:2016-08-31 10:15:51

标签: phpunit symfony

我想知道如何为下面的控制器编写标准单元测试代码。我相信PHPUNIT默认安装在symfony3中,但我也不确定如何执行它。有人可以指导我如何为symfony3编写testcontroller和执行命令。

class RegistrationController extends Controller
{
    /**
     * @Route("/register", name="user_registration")
     * @Security("has_role('ROLE_SUPER_ADMIN')")
     */
    public function userAction(Request $request)
    {
        $user = new User();

        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($request->isMethod('POST')  && $form->isValid()) {            
                $password = $this->get('security.password_encoder')
                    ->encodePassword($user, $user->getPlainPassword());
                $user->setPassword($password);

                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $em->flush();

                $this->get('app.mailer')->sendUserCredentials($user);

                $this->addFlash('notice', 'An account is created');
          }

        return $this->render('masteradmin/account/addUser.html.twig',
            array('form' => $form->createView())
        );
    }

    /**
     * @Route(
     *     "/user/edit/{id}",
     *      requirements={"id" = "\d+"},
     *      name="user_edit"
     * )
     */
    public function editUserAction(User $user, Request $request)
    {
        if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
            throw new AccessDeniedException();
        }

        $em = $this->getDoctrine()->getManager();

        $id = $request->attributes->get('id');

        if (!$user = $em->getRepository('AppBundle:User')->findOneById($id)) {
            throw new NotFoundHttpException('user details not found.');
        }

        $form = $this->createForm(UserType::class, $user)
                    ->remove('plainPassword');

        $form->handleRequest($request);
        $data = $form->getData();

        if ($form->isValid()) {            
            $em->persist($user);
            $em->flush();

            $this->addFlash('notice', 'Account information is updated');

            return $this->redirectToRoute('user_list');
        }

        return $this->render(
            'masteradmin/account/editUser.html.twig', ['form' => $form->createView()]
        );
    }

0 个答案:

没有答案