2017-06-15 102 views
0

我使用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

回答

1

您需要定義類變量或在方法中注入類。

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的新實例時必須傳遞所有依賴項的實例 –