doushan1863 2014-02-04 10:13
浏览 67
已采纳

Laravel控制器测试,处理重定向

I have a bit of an issue, the below code is from one of the methods within my controller that I'm testing.

The scenario is, you save a record and you're automatically directed to 'viewing' that record. So I am passing in the items id upon save to the redirect...

However, when running the tests I receive 'ErrorException: Trying to get property of non-object' if I pass in the id of the object straight off. So the work around I'm doing the pass the test is a ternary condition to see if the output is an object...surely there must be a better way of doing this?

I'm using Mockery, and have created a mock class/interface for the Projects model which is injected into the Projects main controller.

Here's the method:

public function store()
{
    // Required to use Laravels 'Input' class to catch the form data
    // This is because the mock tests don't pick up ordinary $_POST
    $project = $this->project->create(Input::only('projects'));

    if (count(Input::only('contributers')['contributers']) > 0) {
        $output = Contributer::insert(Input::only('contributers')['contributers']);
    }

    // Checking whether the output is an object, as tests fail as the object isn't instatiated
    // through the mock within the tests
    return Redirect::route('projects.show', (is_object($project)?$project->id:null))
                   ->with('fash', 'New project has been created');
}

And heres the test which is testing the redirected route.

       Input::replace($input = ['title' => 'Foo Title']);


    $this->mock->shouldReceive('create')->once();

    $this->call('POST', 'projects');

    $this->assertRedirectedToRoute('projects.show');
    $this->assertSessionHas('flash');
  • 写回答

1条回答 默认 最新

  • doudun1934 2014-02-04 11:07
    关注

    You have to define the response of your mock when the method create is called to properly simulate the real behavior :

    $mockProject = new StdClass; // or a new mock object
    $mockProject->id = 1;
    $this->mock->shouldReceive('create')->once()->andReturn($mockProject);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用