Is it possible to use dependency injection in unit tests?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bandtank
    Active Community Member
    • Mar 2017
    • 399

    #1

    Is it possible to use dependency injection in unit tests?

    I need to add dependencies to test cases in my extension, which is based on the ext-template repository, but nothing I have tried has worked. The following test runs as expected:
    PHP Code:
    <?php declare(strict_types=1);

    namespace 
    tests\unit\Espo\Modules\MoreDateFilters;

    use 
    PHPUnit\Framework\TestCase;

    class 
    CoreTest extends TestCase
    {
      public function 
    __construct() {
        
    parent::__construct();
      }

      public function 
    testGetWeekStartEnd_date(): void {
        
    $this->assertTrue(true);
      }
    }
    However, adding Log to the constructor does not work:
    PHP Code:
    ...
    use 
    Espo\Core\Utils\Log;
    ...
      public function 
    __construct(
        private 
    Log $log,
      ) {
        
    parent::__construct();
      }
    ... 
    Code:
    PHP Fatal error:  ... Too few arguments ... 0 passed in ... and exactly 1 expected in ...
    Is it possible? If so, how?
  • yuri
    EspoCRM product developer
    • Mar 2014
    • 9268

    #2
    Not possible. It's not supposed to work like that. A test is separate from the application.
    If you find EspoCRM good, we would greatly appreciate if you could give the project a star on GitHub. We believe our work truly deserves more recognition. Thanks.

    Comment

    • bandtank
      Active Community Member
      • Mar 2017
      • 399

      #3
      What about integration tests?

      Comment

      • yuri
        EspoCRM product developer
        • Mar 2014
        • 9268

        #4
        In integration tests, it's possible to use $this->getContainer()->getByClass(ServiceClass:class); Or instantiate with $this->getInjectableFactory(). There are many such usages in the Espo repository.
        If you find EspoCRM good, we would greatly appreciate if you could give the project a star on GitHub. We believe our work truly deserves more recognition. Thanks.

        Comment

        Working...