在不可模拟的遗留代码中提供依赖项
我有一个遗留类,我想快速为其编写一些测试。不幸的是,我们在构造函数中有一个单例调用,目前没有足够的时间来重构它。
function __construct(){
$this->_dbConnect = DbConnect::getInstance();
// very long constructer (sigh) omitted below ...
}
这样做是否可以接受,以便拥有可模拟的遗留代码:
function __construct(DbConnect $dbConnect = null){
$this->_dbConnect = isset($dbConnect) ? $dbConnect : DbConnect::getInstance();
// <snip>
}
I have a legacy class that I quickly want to write a couple of tests for. Unfortunately we have a singleton call in the constructer, and not enough time at present to refactor it as it should.
function __construct(){
$this->_dbConnect = DbConnect::getInstance();
// very long constructer (sigh) omitted below ...
}
Is it acceptable practice to do this, so as to have mockable legacy code :
function __construct(DbConnect $dbConnect = null){
$this->_dbConnect = isset($dbConnect) ? $dbConnect : DbConnect::getInstance();
// <snip>
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想这是一个好的开始。话又说回来,如果您要重构整个应用程序,您可能需要考虑仅通过构造函数请求 DatabaseConnection,并更改将创建该对象的所有调用。如果您现在只专注于测试该类,那么您的解决方案是完全可以接受的。
It's a good start, I guess. Then again, if you're going to refactor the whole application, you might want to consider just requesting the DatabaseConnection via the constructor, and change all calls that would create that object. If you're only focused on testing that exact class right now, your solution is totally acceptable.
如果您只想测试此类 - 是,那么它就是普通代码。
很抱歉只回答了一行,但您的问题已经包含答案了:)
If you want to test only this class - yes, it's normal code.
Sorry for 1-line answer, but your question contains answer already :)