Laravel - 使用Doctrine时的phpUnit测试

问题描述:

我使用Laravel + Doctrine(而不是Eloquent)+ Angular Routing创建了一个项目。我决定使用PHP单元测试来测试API(控制器,存储库)其实我在测试一个简单的方法时产生了一个错误。这里是我的代码:Laravel - 使用Doctrine时的phpUnit测试

DoctorineRestaurantRepositoryTest.php:

class RestaurantTest extends TestCase 
    { 
     private $DoctrineRepository; 
     public function setUp() { 
      $this->DoctrineRepository = DoctrineRestaurantRepository::class; 
      } 
     /** @test */ 
     public function validator() 
     { 
      $this->DoctrineRepository->setTestVariable(3); 
      $this->assertEquals($this->DoctrineRepository->getTestVariable(), 3); 
     } 
     . 
     . 
     . 
    } 

我的库文件:(DoctrineRestaurantRepository.php

class DoctrineRestaurantRepository extends DoctrineBaseRepository 
{ 

    private $testVariable = 0; 

    /** 
    * @return int 
    */ 
    public function getTestVariable() 
    { 
     return $this->testVariable; 
    } 

    /** 
    * @param int $testVariable 
    */ 
    public function setTestVariable($testVariable) 
    { 
     $this->testVariable = $testVariable; 
    } 

    . 
    . 
    . 
} 

我跑的测试,它给了一个错误:

Call to a member function setTestVariable() on string 

任何解决它的建议?

+0

你有没有在__construct注入DoctrineRepository?我认为你需要检查它是否被注入。 –

+1

$ this-> DoctrineRepository是在哪里创建的?听起来像你引用像DoctrineRepository :: class这样的类名。 – btl

+0

@btl我编辑了我的问题。 – AFN

您需要定义类变量或在方法中注入类。

Solution 1

adding new object to the class variable

use DoctrineRestaurantRepository; 

class RestaurantTest extends TestCase 
{ 
    private $DoctrineRepository; 

    public function __construct() 
    { 
     $this->DoctrineRepository = new DoctrineRestaurantRepository; 
    } 
    /** @test */ 
    public function validator() 
    { 
     $this->DoctrineRepository->setTestVariable(3); 
     $this->assertEquals($this->DoctrineRepository->getTestVariable(), 3); 
    } 
    . 
    . 
    . 
} 

Solution 2

using dependency injection

use DoctrineRestaurantRepository; 

class RestaurantTest extends TestCase 
{ 
    private $DoctrineRepository; 

    public function __construct(DoctrineRestaurantRepository $repository) 
    { 
     $this->DoctrineRepository = $repository; 
    } 
    /** @test */ 
    public function validator() 
    { 
     $this->DoctrineRepository->setTestVariable(3); 
     $this->assertEquals($this->DoctrineRepository->getTestVariable(), 3); 
    } 
    . 
    . 
    . 
} 
+0

方法1的结果:PHP致命错误:Uncaught TypeError:传递给DoctrineORM的参数1 \ DoctrineBaseRepository :: __ construct()必须是一个实例学说\ ORM \的EntityManager的,没有给出,堪称DoctorineRestaurantRepositoryTest.php第18行和定义在/DoctrineORM/DoctrineBaseRepository.php:22 – AFN

+0

而且__construct在DoctrineBaseRepository看起来是这样的: 公共职能__construct($的EntityManager EM) – AFN

+0

然后创建DoctrineRestaurantRepository的新实例时必须传递所有依赖项的实例 –