How do I mock a method called within the constructor in a PHP unit test? -
i'm having trouble unit testing class has method called within constructor. don't understand how mock this. perhaps should use 'setup' method of phpunit?
i'm using mockery library. there better tool this?
class totest { function __construct() { $this->methodtomock(); // need mock future tests } // methods class }
any suggestions appreciated.
if class difficult instantiate test, code smell class doing or doing work in constructor.
http://misko.hevery.com/code-reviewers-guide/
flaw #1: constructor real work
warning signs
- new keyword in constructor or @ field declaration
- static method calls in constructor or @ field declaration
- anything more field assignment in constructors
- object not initialized after constructor finishes (watch out initialize methods)
- control flow (conditional or looping logic) in constructor
- code complex object graph construction inside constructor rather using factory or builder
- adding or using initialization block
whatever methodtomock
function in constructor needs rethought. mentioned in other answers, want use dependency injection pass in things class doing.
rethink class doing , refactor easier test. has benefit of making class easier reuse , modify later on.
Comments
Post a Comment