views:

1164

answers:

7

What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this:

getMock($className, $methods = array(), array $arguments = array(),
        $mockClassName = '', $callOriginalConstructor = TRUE,
        $callOriginalClone = TRUE, $callAutoload = TRUE)

I don't get it to work. It still complains about the constructor argument, even with $callOriginalConstructor set to false.

A: 

Maybe you are doing too much in your constructor. Consider moving everything apart from simple property setting and dependency injection into other methods.

Constructors considered harmful

Ken
A: 

I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.

A: 

There is, an ugly one.

Use unserialize() on a previously serialized object. PHP will call __wakeup instead of __construct.

porneL
A: 

Can you post your constuctor and test code?

cbrulak
A: 

Perhaps you need to create a stub to pass in as the constructor argument. Then you can break that chain of mock objects.

Ryono
A: 

PHPUnit is designed to call the constructor on mocked objects; to prevent this you should either:

  1. Inject a mock object as a dependency into the object you're having trouble mocking
  2. Create a test class that extends the class you're trying to call that doesn't call the parent constructor
silfreed
+10  A: 

Did any of you actually read the question before you answered it?

    // Get a Mock Soap Client object to work with.
    $classToMock = 'SoapClient';
    $methodsToMock = array('__getFunctions');
    $mockConstructorParams = array('fake wsdl url', array());
    $mockClassName = 'MyMockSoapClient';
    $callMockConstructor = false;
    $mockSoapClient = $this->getMock($classToMock,
                                     $methodsToMock,
                                     $mockConstructorParams,
                                     $mockClassName,
                                     $callMockConstructor);

You guys should try knowing what you are talking about before you answer a question. The original poster even showed you the getMock signature ...

Matthew Purdon
This seems to be almost what I want. I want to call the getMock with only class to be mocked and the $callMockConstructor. How? something like this: $this->getMock($classToMock, $callMockConstructor). The only thing I could think of is to go in the source of PHPUnit and change it to default = false.
Gutzofter
I changed the default to false in testcase.php. You would think it would be set for false by default. Mocking a constructor seems very odd
Gutzofter
OBTW, Thank You!
Gutzofter