2015-04-21 45 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

噢,你说得对,谢谢,我添加了示例代码。 –