沃梦达 / 编程问答 / php问题 / 正文

如果该函数应该杀死 PHP,您如何使用 PHPUnit 测试该函数?

How do you use PHPUnit to test a function if that function is supposed to kill PHP?(如果该函数应该杀死 PHP,您如何使用 PHPUnit 测试该函数?)

本文介绍了如果该函数应该杀死 PHP,您如何使用 PHPUnit 测试该函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个名为 killProgram 的类的方法,它旨在发送一个 hTTP 重定向然后杀死 PHP.

Essentially I have a method of a class called killProgram, which is intended to send a hTTP redirect and then kill PHP.

我应该如何测试这个?当我运行 phpunit 时,它不会为该测试返回任何内容,并完全关闭.

How am I supposed to test this? When I run phpunit it doesn't return anything for that test, and closes completely.

现在我正在考虑让 killProgram 函数抛出一个不应被处理的异常,这样我就可以断言抛出了一个异常.

Right now I'm considering having the killProgram function throw an exception which shouldn't get handled, which would allow me to assert that an exception was thrown.

有没有更好的办法?

推荐答案

由于每个测试都由同一个 PHPUnit 进程运行,如果你在 PHP 代码中使用 exit/die,你会杀死一切——正如你所注意到的 ^^

As every tests are run by the same PHPUnit process, if you use exit/die in your PHP code, you will kill everything -- as you noticed ^^

所以,你必须找到另一个解决方案,是的——比如返回而不是死亡;或者抛出异常(你可以测试一些被测试的代码是否抛出了预期的异常).

So, you have to find another solution, yes -- like returning instead of dying ; or throwing an exception (you can test if some tested code has thrown an expected exception).

也许是 PHPUnit 3.4 和它的 --process-isolation 开关(参见 可选执行每个测试都使用单独的 PHP 进程)可能帮助(不会让所有东西都死掉),但您仍然无法获得测试,如果 PHPUnit 没有得到控制权.

Maybe PHPUnit 3.4 and it's --process-isolation switch (see Optionally execute each test using a separate PHP process) might help (by not having everything dying), but you still wouldn't be able to get the result of the test, if PHPUnit doesn't get the control back.

我遇到过几次这个问题;通过返回而不是死亡来解决它——如果需要,甚至返回几次,以便在调用堆栈中返回足够高"^^
最后,我想我的应用程序中不再有任何死亡"了......在考虑 MVC 时,这可能会更好,顺便说一句.

I've had this problem a couple of times ; solved it by returning instead of dying -- even returning several times, if needed, to go back "high enough" in the call stack ^^
In the end, I suppose I don't have any "die" anymore in my application... It's probably better, when thinking about MVC, btw.

这篇关于如果该函数应该杀死 PHP,您如何使用 PHPUnit 测试该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果该函数应该杀死 PHP,您如何使用 PHPUnit 测试该函数?

基础教程推荐