首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何测试Laravel 5控制器方法

如何测试Laravel 5控制器方法
EN

Stack Overflow用户
提问于 2015-04-22 03:11:27
回答 2查看 12.8K关注 0票数 10

我们有Laravel 5控制器方法:

代码语言:javascript
运行
复制
public function getInput()
{
    $input = \Request::all();
    $links = $input['links'];
    $this->startLinks =  explode("\n", $links);
    return $this;
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-22 03:54:40

这看起来像是一个可能不属于控制器的方法。如果您对测试很认真,我强烈建议您阅读有关存储库模式的内容。在测试时,将所有内容从controllers.=中抽象出来将使您的工作变得容易得多

话虽如此,但这仍然是非常可测试的。主要的想法是找出需要测试的东西,并只测试它。这意味着我们不关心依赖项在做什么,只关心它们正在做什么,并返回方法的其余部分需要的东西。在本例中,它是Request外观。

然后,您需要确保正确设置了变量,并且该方法返回了该类的实例。它实际上是非常直接的。

应该是这样的.

代码语言:javascript
运行
复制
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));
}
票数 14
EN

Stack Overflow用户

发布于 2015-04-22 03:56:06

我想你是在找this

如果你的测试类扩展了TestCase,你会得到很多帮助器方法,这些方法会帮你完成繁重的工作。

代码语言:javascript
运行
复制
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进一步扩展了这一功能。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29781103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档