jeudi 7 juillet 2016

PHPUnit mock faster and don't repeat the code

I like to ask you about your practice of writing unit test, how to mock object and don't repeat the code?

I am using Symfony2 framework and for example I have many bundles with custom validators. When me and the rest of my team writing unit test we repeat the code of mocking Constraint, ExecutionContext, ConstraintViolationBuilderInterface. I know that we can create trait or abstract class or something else where we can store code responsible for mocking but before I will start doing this I like to know your best practices.

My first idea was to create a class/trait which will store for example mock of all repositories. Example:

class MockRepositoryHelper extends \PHPUnit_Framework_TestCase
{
    public function getUserRepositoryMock()
    {
        return $this->prophesize(UserRepository::class);
    }

    // next repositories getters
}

and then use this code in real test case:

class EmailValidator extends \PHPUnit_Framework_TestCase
{
    private $mockRepositoryHelper;

    public function setUp()
    {
        parent::setUp();
        $this->mockRepositoryHelper = new MockRepositoryHelper();
    }

    /**
     * @test
     */
    public function it_should_find_user()
    {
        $userRepository = $this->mockRepositoryHelper->getUserReposioryMock();
        $userRepository->findUser(Argument::type('string'))->willReturn(null);

        // rest of the test
    }
}

Of course this is only pseudo code what I imagined, my first thought. What are yours ideas?

Basically I am asking how to write unit test faster and don't repeat the code?

Aucun commentaire:

Enregistrer un commentaire