CakePHP的testAction方法可以在重定向调用中幸存吗? [英] Can CakePHP's testAction method survive a redirect call?

查看:52
本文介绍了CakePHP的testAction方法可以在重定向调用中幸存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用CakePHP框架和SimpleTest编写单元测试。该文档描述了当您的控制器使用testAction方法时出现的问题将浏览器重定向到另一个页面。希望寄出带有可能的修复程序的链接,但该链接已断开。 / p>

有人能进行这项工作吗?



我发现了有关使用部分模拟对象来覆盖重定向调用,但这似乎不适用于testAction方法。我怀疑我必须以某种方式向调度程序注册模拟控制器。



这是一个 Google网上论坛上的类似问题

解决方案

我需要一些工作,所以我想把它发布在这里。我不确定自己是否满意。



如果您希望能够测试重定向,请更改以下内容:

  $ this-> redirect(array('action'=>'index')); 

为此:

  $ this-> redirect(array('action'=>'index'),null,false); 
的收益已重定向到索引;

现在您的测试可以像这样:

  $ data = array(...); 
$ result = $ this-> testAction(
'/ people / edit / 1',
array('method'=>'post','data'=> $数据));
$ this-> assertEqual(
重定向到索引,
$ result);

控制器重定向方法的问题是默认情况下它调用exit()并退出整个测试套件。此版本将false传递给重定向方法的$ exit参数,然后使用 return 而不是exit()。尽管返回值与重定向标头一起回显到浏览器,但返回值只是供测试用例验证的内容。不过,只要是一条小消息,我就不会发现任何问题。



似乎没有任何重要的代码可以在执行之后调用 return 而不是exit()时的控制器方法。快速测试表明页面正常运行。


I'm starting to write unit tests using the CakePHP framework and SimpleTest. The documentation describes a problem with the testAction method when your controller redirects the browser to another page. There is a hopeful note with a link to a possible fix, but the link is broken.

Has anybody gotten this working? Know how to find where that broken link should point?

I found a discussion of using partial mock objects to override the redirect call, but that doesn't seem to work with the testAction method. I suspect I'd have to somehow register the mock controller with the dispatcher.

Here's a similar question on Google groups.

解决方案

I got something to work, so I thought I'd post it here. I'm not sure if I'm happy with it yet.

If you want to be able to test a redirect, change this:

$this->redirect(array('action'=>'index'));

to this:

$this->redirect(array('action'=>'index'), null, false);
return 'redirected to index';

Now your test can look something like this:

$data = array(...);
$result = $this->testAction(
    '/people/edit/1',
    array('method' => 'post', 'data' => $data));
$this->assertEqual(
    'redirected to index',
    $result);

The problem with the controller's redirect method is that it calls exit() by default, and that exits out of the entire test suite. This version passes false to the redirect method's $exit parameter, and then uses return instead of exit(). The return value is just something for the test case to validate if you like, although it is echoed to the browser along with the redirect header. As long as it's a small message, though, I don't see any problem with that.

There doesn't seem to be any significant code that might execute after the controller method when we call return instead of exit(). A quick test shows that the page behaves normally.

这篇关于CakePHP的testAction方法可以在重定向调用中幸存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆