简体   繁体   中英

Symfony2 unit testing cannot instantiate class in test class

I am working with Symfony2 and trying to write some PHPUnit test for one of my classes.

This is what I have done so far following Symfony2 testing Docs i created a folder under Tests directory with a file myClassTest.php ini it:

<?php

namespace Test\TestBundle\Tests\Template;

use Test\TestBundle\Dto\Template\myTemplate;

class myTemplateTest extends \PHPUnit_Framework_TestCase
{

    public function testMyMethod()
    {
        $test = new myTemplate();
    }
}

This is myTemplate:

<?php
namespace Test\TestBundle\Dto\Template;

use Test\TestBundle\Doctrine\DatabaseRepository;
use Test\TestBundle\Validation\ValidationClass;

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;
    }
}

Errors:

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

More Errors:

This error points to the injected service in the construct $validation

Dev/project/src/Test/TestBundle/Dto/Template/myTemplate.php:42

This error corresponds to the instantiate class of myTemplate class

Dev/project/src/Test/TestBundle/Tests/Dto/Template/myTemplateTest.php:15

I understand the errors well i think I do but i have no idea how to fix it and these errors are shown when i run phpunit test.

For testing with PHPUnit, you should use Mocks and Stubs for imitation logic in your depends classes.

Before initialize myTemplate in test case, you should create a mock of this objects, or create original objects.

$validationMock = $this->getMock('ValidationClass');
$dbRepositoryMock = $this->getMock('DatabaseRepository');

$myTemplate = new myTemplate($validationMock, $dbRepositoryMock);

And after you can use invocation system for control called methods.

For more information, please visit PHPUnit site: https://phpunit.de/manual/current/en/test-doubles.html

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