2015-04-21 67 views
3

我們有Laravel 5個控制器方法:如何測試Laravel 5個控制器方法

public function getInput() 
{ 
    $input = \Request::all(); 
    $links = $input['links']; 
    $this->startLinks = explode("\n", $links); 
    return $this; 
} 

我們如何測試這個單一的方法?我不明白如何將POST請求與數據傳遞給此方法? 以及如何在我的測試方法中創建此控制器類的實例?

回答

6

這看起來像一個可能不應該屬於控制器的方法。如果您認真對待測試,我強烈建議您閱讀存儲庫模式。當測試時,它會讓你的生活變得更容易,從控制器中抽象出所有東西。=

儘管如此,這仍然是非常可測試的。主要想法是找出需要測試的東西並且只測試一下。這意味着我們不關心依賴關係在做什麼,只關心他們在做什麼,並返回剩下的方法需要的東西。在這種情況下,它是Request外觀。

然後,您要確保變量設置得當,並且該方法返回該類的一個實例。它實際上最終是非常簡單的。

應該是這個樣子......

public function testGetInput() 
{ 
    $requestParams = [ 
     'links' => "somelink.com\nsomeotherlink.com\nandanotherlink.com\ndoesntmatter.com" 
    ]; 

    // Here we are saying the \Request facade should expect the all method to be called and that all method should 
    // return some pre-defined things which we will use in our asserts. 
    \Request::shouldReceive('all')->once()->andReturn($requestParams); 

    // Here we are just using Laravel's IoC container to instantiate your controller. Change YourController to whatever 
    // your controller is named 
    $class = App::make('YourController'); 

    // Getting results of function so we can test that it has some properties which were supposed to have been set. 
    $return = $class->getInput(); 

    // Again change this to the actual name of your controller. 
    $this->assertInstanceOf('YourController', $return); 

    // Now test all the things. 
    $this->assertTrue(isset($return->startLinks)); 
    $this->assertTrue(is_array($return->startLinks)); 
    $this->assertTrue(in_array('somelink.com', $return->startLInks)); 
    $this->assertTrue(in_array('nsomeotherlink.com', $return->startLInks)); 
    $this->assertTrue(in_array('nandanotherlink.com', $return->startLInks)); 
    $this->assertTrue(in_array('ndoesntmatter.com', $return->startLInks)); 
} 
+0

謝謝你的回答是 - 這就是我需要的!但是,當我把這條線我的測試: '\ Request :: shouldReceive('all') - > once() - > andReturn($ requestParams);' 當im運行phpunit我收到此異常: 'PHP致命錯誤:Class'Mockery'找不到/var/www/site.loc/www/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 86 [Symfony \ Component \調試\例外\ FatalErrorException] 類'嘲笑'找不到' – errogaht

+0

請你能幫忙嗎? – errogaht

+0

對不起,我忘了使用嘲笑。查看https://github.com/padraic/mockery/tree/master瞭解安裝方向。應該只是'composer.json'中的一個新的必需項目。 – user3158900

2

我認爲你正在尋找this

如果你的測試類擴展了TestCase,你會得到很多幫助你的方法。

function testSomething() { 
    // POST request to your [email protected] 
    $response = $this->action('POST', '[email protected]', ['links' => 'link1 \n link2']); 
    // you can check if response was ok 
    $this->assertTrue($response->isOk(), "Custom message if something went wrong"); 
    // or if view received variable 
    $this->assertViewHas('links', ['link1', 'link2']); 
} 

Codeception甚至進一步擴展了該功能。

+1

噢,你說得對,謝謝,我添加了示例代碼。 –