欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHPUnit Exception : Serialization of closure is not allowed

程序员文章站 2022-05-08 20:02:55
...
Not technically related to your issue. However, I had a really hard time trying to solve the "Serialization of 'Closure' is not allowed" issue while using PHPUnit, and this question is the top Google result.

The problem comes from the fact that PHPUnit serializes all the $GLOBALS in the system to essential back them up while the test is running. It then restores them after the test is done.

However, if you have any closures in your GLOBAL space, it's going to cause problems. There's two ways to solve it.

You can disable the global backup procedure totally by using an annotation.

/**

* @backupGlobals disabled

*/

class MyTest extends PHPUnit_Framework_TestCase

{

// ...

}

Or, if you know which variable is causing the problem (look for a lambda in var_dump($GLOBALS)), you can just blacklist the problem variable(s).

class MyTest extends PHPUnit_Framework_TestCase

{

protected $backupGlobalsBlacklist = array('application');

// ...

}

项目在PHPUNIT单元测试时报错:"Serialization of 'Closure' is not allowed",这里因为PHPUNIT把所有的$GLOBALS都系列化了,然后等执行完再释放,所以如果你的全局域里有闭包的话就会报错为 ‘对闭包的系列化是不允许的’,这只是因为PHPUNIT和机制造成的,和application层面无关。解决方法就是像上面那样,在PHPUNIT单元测试的类前面加一个声明,禁用backupGlobals,翻译为全局回溯?