开发者

Feeding a dependency in unmockable legacy code

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) omit开发者_如何转开发ted 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>
}


Is it acceptable practice to do this, so as to have mockable legacy code :

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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜