用PHP测试cookie的单元 [英] Unit testing cookies in PHP

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

问题描述

依赖于会话/ cookie信息的单元测试功能的默认做法是使用抽象库。但是如果我想编写和单元测试这个抽象库呢? PHP setcookie 函数的文档说明cookie将会可在下次请求时使用。使用命令行工具进行测试,没有请求这样的东西。那么我如何才能对正确的cookie设置进行单元测试呢?

The default practice for unit testing functionality that relies on session/cookie information is to use an abstraction library. But what if I want to write and unit test this abstraction library? The documentation for the PHP setcookiefunction says that the cookie will be available on the next request. Using a command line tool for testing, there is no such thing as a "request". So how can I unit test the correct cookie settings?

我想测试我的抽象库是否正确设置了 setcookie 函数的所有参数。这些参数将根据特定条件和方法调用进行设置。

I want to test if all the parameters of the setcookie function are set correctly by my abstraction library. Those parameters will be set according to certain conditions and method calls.

我能想到的唯一解决方案是模拟 setcookie 具有 runkit 扩展名的功能,我不想安装它。其他想法?

The only solution I can think of is to mock the setcookie function with the runkit extension, which I don't want to install. Other ideas?

推荐答案

我找到了另一种非常简单的解决方案:围绕PHP的类包装器 setcookie 功能很简单,不需要进行单元测试:

I found another, very simple solution: A class wrapper around the PHP setcookie function that is so simple, it does not need to be unit tested:

/**
 * Wrapper around setcookie function for better testability
 */ 
class Cookiesetter {
  public function setcookie($name, $value = "",  $expire = 0,  $path = "", 
    $domain = "", $secure = false, $httponly = false) {
    return setcookie($name, $value,  $expire, $path, $domain, $secure, $httponly);
  }
}

setcookie 方法。这有额外的好处,我可以实现其他方法,如 expireCookie

The setcookie method can then be mocked. This has the additional benefit that I can implement other methods like expireCookie.

这篇关于用PHP测试cookie的单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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