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.

6
  • yes, "refactor the code" - its a legacy code.... Commented Aug 23, 2015 at 20:55
  • 1
    possible duplicate of phpunit avoid constructor arguments for mock Commented Aug 23, 2015 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! Commented Aug 23, 2015 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. Commented Aug 24, 2015 at 9:41
  • 1
    You mean constructor, not controller, @WouterJ. Commented Aug 24, 2015 at 17:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.