Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Symfony2 models using PHPUnit

I've been trying to test a model in a Symfony2 project, but I don't know how to get the entity manager to save and retrive records.

Can anyone point me to the right docs for this?

like image 253
nerohc Avatar asked Sep 06 '11 00:09

nerohc


People also ask

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

What is PHPUnit testing?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

Why do we use PHPUnit?

With unit testing we test each component of the code individually. All components can be tested at least once. A major advantage of this approach is that it becomes easier to detect bugs early on. The small scope means it is easier to track down the cause of bugs when they occur.

Which method is used to create a mock with PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.


1 Answers

In order to test your models, you can use setUp() method. link to docs

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MyModelTest extends WebTestCase
{
    /**
     * @var EntityManager
     */
    private $_em;

    protected function setUp()
    {
        $kernel = static::createKernel();
        $kernel->boot();
        $this->_em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
        $this->_em->beginTransaction();
    }

    /**
     * Rollback changes.
     */
    public function tearDown()
    {
        $this->_em->rollback();
    }

    public function testSomething()
    {
        $user = $this->_em->getRepository('MyAppMyBundle:MyModel')->find(1);
    }

Hope this helps you

like image 105
Benjamin Lazarecki Avatar answered Oct 02 '22 05:10

Benjamin Lazarecki