热搜:NVER node 开发 php

PHPUnit Exception : Serialization of closure is not allowed

2024-07-23 21:55:02
PHPUnit Exception : Serialization of closure is not allowed

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,翻译为全局回溯?