带有需要发送标题的项目的单元测试 [英] Unit Testing with items that need to send headers

查看:62
本文介绍了带有需要发送标题的项目的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在与PHPUnit一起尝试并开发与我正在写的东西相关的测试,但是,我目前正在编写会话管理器,并且在这样做时遇到了问题...

I'm currently working with PHPUnit to try and develop tests alongside what I'm writing, however, I'm currently working on writing the Session Manager, and am having issues doing so...

Session处理类的构造函数是

The constructor for the Session handling class is

private function __construct()
{
    if (!headers_sent())
    {
        session_start();
        self::$session_id = session_id();
    }
}

但是,随着PHPUnit在开始测试之前发出文本,对该对象的任何测试都会返回失败的测试,因为已经发送了HTTP标头" ...

However, as PHPUnit sends out text before it starts the testing, any testing on this Object returns a failed test, as the HTTP "Headers" have been sent...

推荐答案

好吧,您的会话管理器基本上是被设计破坏的.为了能够测试某些东西,必须能够将其与副作用隔离开.不幸的是,PHP的设计方式是鼓励自由使用全局状态(echoheaderexitsession_start等).

Well, your session manager is basically broken by design. To be able to test something, it must be possible to isolate it from side effects. Unfortunately, PHP is designed in such a way, that it encourages liberal use of global state (echo, header, exit, session_start etc. etc.).

您能做的最好的事情是隔离组件中的副作用,这些副作用可以在运行时进行交换.这样,您的测试就可以使用模拟对象,而实时代码则使用具有真正副作用的适配器.您会发现这不适用于单例,我想您正在使用单例.因此,您必须使用其他机制才能将共享库分发到您的代码中.您可以从静态注册表开始,但是如果您不介意学习的话,甚至还有更好的解决方案.

The best thing you can do, is to isolate the side-effects in a component, that can be swapped at runtime. That way, your tests can use mocked objects, while the live code uses adapters, that have real side-effects. You'll find that this doesn't play well with singletons, which I presume you're using. So you'll have to use some other mechanism for getting shared objects distributed to your code. You can start with a static registry, but there are even better solutions if you don't mind a bit of learning.

如果您不能这样做,则始终可以选择编写集成测试.例如.使用与 WebTestCase 等效的PHPUnit.

If you can't do that, you always have the option of writing integration-tests. Eg. use the PHPUnit's equivalent of WebTestCase.

这篇关于带有需要发送标题的项目的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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