如何测试Laravel 5控制器方法

时间:2015-04-21 19:11:27

标签: php laravel phpunit laravel-5

我们有Laravel 5控制器方法:

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

我们如何测试这种方法?如何将带有数据的POST请求传递给此方法?以及如何在我的测试方法中创建此控制器类的实例?

2 个答案:

答案 0 :(得分:9)

这看起来像一个可能不属于控制器的方法。如果您认真考虑测试,我强烈建议您阅读存储库模式。在测试时,它会让您的生活变得更加容易,从控制器中抽象出来。=

尽管如此,这仍然是非常可测试的。主要想法是找出需要测试的内容,并且只测试它。这意味着我们不关心依赖项正在做什么,只关心它们正在做什么并返回方法的其余部分所需要的东西。在这种情况下,它是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));
}

答案 1 :(得分:3)

我认为您正在寻找this

如果您的测试类扩展TestCase,您将获得许多辅助方法,这些方法将为您提供繁重的工作。

function testSomething() {
    // POST request to your controller@action
    $response = $this->action('POST', 'YourController@yourAction', ['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进一步扩展了此功能。