使用 PHPUnit 测试 cookie 和会话,如何? [英] Using PHPUnit to test cookies and sessions, how?

查看:29
本文介绍了使用 PHPUnit 测试 cookie 和会话,如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PHPUnit 可以很容易地测试原始 PHP 代码,但是那些严重依赖 cookie 的代码呢?会话可能是一个很好的例子.

With PHPUnit it's quite easy to test raw PHP code, but what about code that heavily relies on cookies? Sessions could be a good example.

有没有一种方法不需要我在测试期间使用数据设置 $_COOKIE?这感觉像是一种 hacky 的做事方式.

Is there a method that doesn't require me to setup $_COOKIE with data during my test? It feels like a hacky way of doing things.

推荐答案

这是代码的常见问题,尤其是遗留的 PHP 代码.常用的技术是进一步抽象相关对象中的 COOKIE/SESSION 变量,并使用控制反转技术将这些依赖关系拉入范围.

This is a common problem with code, especially lagacy PHP code. The common technique used is to further abstract the COOKIE/SESSION variables in related objects and using inversion of control technique(s) to pull those dependencies into scope.

http://martinfowler.com/articles/injection.html

现在在执行测试之前,您将实例化 Cookie/Session 对象的模拟版本并提供默认数据.

Now before you execute a test you would instantiate a mock version of a Cookie/Session object and provide default data.

我想,通过在执行测试之前简单地覆盖超级全局值,可以使用遗留代码实现相同的效果.

I imagine, the same effect can be achieved with legacy code by simply overriding the super global value before executing the test.

干杯,亚历克斯

这篇关于使用 PHPUnit 测试 cookie 和会话,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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