I'm having trouble unit testing a class that has a method called within the constructor. I don't understand how to mock this. Perhaps I should use the 'setUp' method of phpUnit?
I'm using the Mockery library. Is there is a better tool than this?
class ToTest
{
function __construct() {
$this->methodToMock(); // need to mock that for future tests
}
// my methods class
}
Any suggestions would be appreciated.
If you class is difficult to instantiate to test, that is a code smell that your class is doing too much or doing work in the constructor.
http://misko.hevery.com/code-reviewers-guide/
Flaw #1: Constructor does Real Work
Warning Signs
Whatever your methodToMock
function does in your constructor needs to be rethought. As mentioned in the other answers, you probably want to use dependency injection to pass in things that your class is doing.
Rethink what your class is actually doing and refactor so that it is easier to test. This also has the benefit of making your class easier to reuse and modify later on.
The problem here is that the method can not be mocked as the object is not yet instantiated. sectus answer is valid but maybe not very flexible, as it can be difficult to change the behavior of the mocked method on different tests.
You can create another class that does the same as the method you want to mock, and have an instance of that class passed as a constructor argument. That way you can pass a mock class on your test. Usually the problem you're having is a smell of a class doing too many things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With