使用需要发送标头的项目进行单元测试 [英] Unit Testing with items that need to send headers

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

问题描述

我目前正在与 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.

如果你不能这样做,你总是可以选择编写集成测试.例如.使用 PHPUnit 相当于 WebTestCase.

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天全站免登陆