3

I want to mock the constructor like any other methods. I also added a willReturnCallback clause, which does not seem to work. I mean, it all works with methods, but not with the constructor.

$mock = $this->getMock ('MyClass', array(), array(), '', false);
$mock->expects($this->once())->method('__construct')->willReturnCallback(function() { echo 'outputt'; });

so mocking constructor has no effect.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
John Smith
  • 6,129
  • 12
  • 68
  • 123
  • yes, "refactor the code" - its a legacy code.... – John Smith Aug 23 '15 at 20:55
  • 1
    possible duplicate of [phpunit avoid constructor arguments for mock](http://stackoverflow.com/questions/279493/phpunit-avoid-constructor-arguments-for-mock) – Willem Renzema Aug 23 '15 at 20:55
  • 1
    The original constructor is called during mock construction (it just calls the baseclass' constructor). If you don't want that, you can also disable it. However, I wonder why you want to mock the constructor? The point is that unless you explicitly call it (which would be a code smell), creating the mock does the construction, so it's too late to expect a constructor call! – Ulrich Eckhardt Aug 23 '15 at 20:55
  • 1
    Besides all limitations of mocking, a controller can *never* return anything, so the mock doesn't mean anything at the moment. – Wouter J Aug 24 '15 at 09:41
  • 1
    You mean constructor, not controller, @WouterJ. – Ulrich Eckhardt Aug 24 '15 at 17:28
  • yea, in kind you are all true. The problem is, the constructor does more than initialization, it actually "echo"-es something. Nevertheless, I refractored that "legacy" code, I guess that was the only solution – John Smith Aug 25 '15 at 10:13

1 Answers1

2

Adding the relevant comments as community wiki answer because there will never be another answer than "not logically possibly":

The original constructor is called during mock construction (it just calls the baseclass' constructor). If you don't want that, you can also disable it. However, I wonder why you want to mock the constructor? The point is that unless you explicitly call it (which would be a code smell), creating the mock does the construction, so it's too late to expect a constructor call

Besides all limitations of mocking, a controllerconstructor can never return anything, so the mock doesn't mean anything at the moment

Community
  • 1
  • 1
Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111