2016-04-22 120 views
1

有人可以幫助我進行控制器功能測試。無法測試控制器中是否有語句,所以請關注這段代碼。 這個控制器的其他測試是好的,但只有來自「if語句」的代碼不能被測試。Laravel測試If/else語句 - 單元測試

LanguageController.php

class LanguageController extends Controller implements IEntityViewManager 
{ 
    protected $languageRepo; 

    public function __construct(LanguageRepositoryInterface $languageRepo) 
    { 
     $this->languageRepo = $languageRepo; 
    } 

    public function createAction(LanguagePostRequest $request) 
    { 
     $languages = $this->languageRepo->whereCharOrName($request->char, $request->name); 

     if(count($languages) > 0) 
     { 
      return redirect()->back()->withErrors("Already exists")->withInput(); 
     } 

     $language = new Language(); 
     $this->languageRepo->store($language, $request->all()); 

     return redirect()->route('Admin.Language.showAllView'); 
    } 
} 

這裏是我的這個測試測試reqirements:

LanguageControllerTest.php

class LanguageControllerTest extends TestCase 
{ 
    public function __construct($name = NULL, array $data = array(), $dataName = '') 
    { 
     parent::__construct($name, $data, $dataName); 
    } 

    public function setUp() 
    { 
     parent::setUp(); 
    } 

    public function tearDown() 
    { 
     Mockery::close(); 
    } 

    protected function setUpMock() 
    { 
     $mock = Mockery::mock(LanguageRepositoryInterface::class); 
     $this->app->instance(LanguageRepositoryInterface::class, $mock); 

     return $mock; 
    } 

    public function testInvalidInsertLanguage1() 
    { 
     $params = array(
      'char' => 'en', 
      'name' => 'English' 
     ); 

     $mock = $this->setUpMock(); 

     // HELP ME TO TEST IF STATEMENT AND TO REDIRECT BACK WITH ERRORS AND INPUTS 
     // NEED CONTENT 

     $this->action('POST', 'Entities\[email protected]', null, $params); 
    } 

或者,也許我應該避免if語句,並把它在控制器內部的一些其他功能中,但它太複雜了測試,因爲我應該嘲笑這個控制器?

回答

1

您可以執行以下操作,它建立了一個模擬程序,它需要初始化語言的方法。現在既然你只想測試count方法,你只需返回一個包含元素的數組。這將測試你的控制器的重定向部分。我沒有運行這個代碼,但希望你能明白。

public function setUp() 
{ 
    $this->mock = Mockery::mock("LanguageRepositoryInterface"); 
} 

public function testInvalidInsertLanguageRedirect() 
{ 
    $params = array(
     'char' => 'en', 
     'name' => 'English' 
    ); 

    $this->mock 
     ->shouldReceive("whereCharOrName") 
     ->once() 
     ->andReturn([1]); 

    $response = $this->action('POST', 'Entities\[email protected]', null, $params); 
    $this->assertEquals(301, $response->status()); 
} 
+0

我只是試過你的解決方案,它的工作原理(只限於代碼302)。謝啦 ! – Dulo

+0

好的。很高興它的工作! –