我有一个遗留类,我快速想要编写几个测试。不幸的是,我们在构造函数中有一个单例调用,目前没有足够的时间来重构它,因为它应该。在unmockable遗留代码中提供依赖关系
function __construct(){
$this->_dbConnect = DbConnect::getInstance();
// very long constructer (sigh) omitted below ...
}
它是可以接受的做法要做到这一点,这样才能有mockable遗留代码:如果你只需要测试这个类
function __construct(DbConnect $dbConnect = null){
$this->_dbConnect = isset($dbConnect) ? $dbConnect : DbConnect::getInstance();
// <snip>
}
这是在[Sebastian Bergmann关于使用Singletons测试代码的博客文章]中建议的方法(http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html) – Gordon 2011-05-23 10:22:13