简体   繁体   中英

Symfony2 PHPUnit testing class with services

I am working with Symfony2 and trying to do some phpunit testing. The class i am trying to test is has two services injected:

ValidationClass
DatabaseRepository

I have created a test file for this class 'MyTemplateTest.php' under Test/Template directory.

My test file:

<?php

namespace Fun\FunBundle\Tests\Dto\Template;

use Fun\FunBundle\Dto\Template\myTemplate;

class myTemplateTest extends \PHPUnit_Framework_TestCase
{
    public function testbuild()
    {
        $validation = $this->getMock('ValidationClass');
        $database = $this->getMock('DatabaseRepository');

        $confirm = new myTemplate($validation, $database);
    }
}

When i run phpunit -c app/

I get these errors:

Argument 1 passed to Fun\\FunBundle\\Dto\\Template\\myTemplate::__construct() must be an instance of Fun\\FunBundle\\Validation\\ValidationClass, string given, called in Dev/project/src/Fun/FunBundle/Tests/Template/myTemplateTest.php

myTemplate

class myTemplate
{


    /**
     * @var ValidationClass
     */
    private $validate;

    /**
     * @var DatabaseRepository
     */
    private $db;

    /**
     * @param ValidationClass $validation
     * @param DatabaseRepository $databaseRepository
     */
    public function __construct(
        ValidationClass $validation,
        DatabaseRepository $databaseRepository
    ) {
        $this->validate = $validation;
        $this->db = $databaseRepository;
    }
}

I came to a point where I have no idea how I can test myTemplate class :/ I do understand that the errors are relating to the injected services but how do i replicate or do this in my TestmyTemplate file?

I think you'll need to add the FQN (fully qualified name) of these classes to be able to mock properly. So you'll need to prefix ValidationClass with the full namespace, like Some\\Folder\\Validation\\ValidationClass

According to the PHPunit site on defining Mocks , you first call getMockBuilder with the fully-qualified namepace/classname, and then getMock() returns the usable object.

$mock = $this->getMockBuilder('stdClass')
             //->setMethods(array('set')) # to be able to call a method
             ->getMock();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM