這看起來像一個可能不應該屬於控制器的方法。如果您認真對待測試,我強烈建議您閱讀存儲庫模式。當測試時,它會讓你的生活變得更容易,從控制器中抽象出所有東西。=
儘管如此,這仍然是非常可測試的。主要想法是找出需要測試的東西並且只測試一下。這意味着我們不關心依賴關係在做什麼,只關心他們在做什麼,並返回剩下的方法需要的東西。在這種情況下,它是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));
}
謝謝你的回答是 - 這就是我需要的!但是,當我把這條線我的測試: '\ 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
請你能幫忙嗎? – errogaht
對不起,我忘了使用嘲笑。查看https://github.com/padraic/mockery/tree/master瞭解安裝方向。應該只是'composer.json'中的一個新的必需項目。 – user3158900