如何对会话包装类进行单元测试?
我有简单的会话包装类,其中包含 getters 和 setters 来处理 OO 风格的 $_SESSION 。 session_start()
在 __constructor() 中调用。对此类进行单元测试的最佳实践是什么?
由于我们从 CLI 运行单元测试 - 我们无法真正创建会话,但我们可以在测试设置或测试中的任何其他位置定义 $_SESSION 变量。模拟网络会话的最佳实践是什么?也许我应该创建某种测试环境,并设置所有服务器变量?
- PHPUnit_Framework_Error_Warning : E_WARNING: session_start(): 无法发送会话 cookie - 已发送的标头(输出从 C:\Users\Kir\AppData\Local\Temp\phpunit_go_Kir.php:770 开始) - 如何避免这种情况?如何防止 PHP 单元测试输出
测试于 12:59 开始 ...
PS:很抱歉有问题,但我昨天才开始编写单元测试,目前还没有足够的经验。
谢谢。
I have simple session wrapper class with getters and setters to deal with $_SESSION in OO style. session_start()
is called in __constructor(). What is the best practice to unit test this class?
As we're running unit tests from CLI - we can't truly create session, but we can define $_SESSION variables in test setup or any other place in test. What is the best practice to emulate web session? Maybe I should create some kind of testing environment with all server variables being set?
PHPUnit_Framework_Error_Warning : E_WARNING: session_start(): Cannot send session cookie - headers already sent by (output started at C:\Users\Kir\AppData\Local\Temp\phpunit_go_Kir.php:770) - how to avoid this? How to prevent PHP Unit Test output
Testing started at 12:59 ...
PS: Sorry for questions, but I've started to write unit tests only yesterday and I have no enough experience at the moment.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在代码中调用 session_start 会将您绑定到 PHP 的 session_start 实现。实际上,会话的概念在 CLI 中没有什么意义。您可以在您的类中使用以下代码来保护您的 session_start 调用:
我将我的会话类保留为与此代码相关(加上用于 session_id 的简单 id 函数)。由于 session_start 调用已受到防范,因此可以继续在 CLI 上进行测试。但实际上测试我粘贴的代码很困难。您可以通过在正常 CLI 测试之外的浏览器下观察来测试它。至少所有其他 CLI 测试现在都不会受到 session_start 调用的影响。
Calling session_start in your code binds you to PHP's session_start implementation. Actually, the idea of a session makes little sense in CLI. You can guard your session_start calls with the following code in your class:
I have kept my session class to be just about this code (plus a simple id function for session_id). Testing on the CLI can continue as the session_start call has been guarded against. Actually testing the code I pasted is hard though. You can test it by observation under a browser outside of your normal CLI testing. At least all of your other CLI testing will now be unaffected by session_start calls.