Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

getMock should always use munged name by default #678

Closed
splondike opened this Issue · 1 comment

2 participants

@splondike

A mock created with getMock('MyClass') will register a new class called 'MyClass' if one doesn't already exist.

This caused some problems for me with the CakePHP class loader which uses class_exists to decide whether to load something. I'd forgotten to include the class I was mocking, and hence PHPUnit made one for me. This caused a test in an unrelated class to fail because the application tried to use a non-existent method on the mock object.

I think it would be both more consistent and safer if PHPUnit used the munged class name in both the existing class and no existing class cases. If the user wants a specific name, they can use setMockClassName. Ideally we'd be unloading the mock classes after each test case, but I understand you can't do this in PHP.

A test case:

<?php
class MockBleedsTest extends PHPUnit_Framework_TestCase {
   public function testOne() {
      $this->getMock('FakeClass');
      $this->assertFalse(class_exists('FakeClass'));
   }
}
@edorian
Collaborator

If he had the change to redo the whole mocking API this is something I'd surely change but as it is now people depend on that behavior and we'd break a lot of existing code so we can't really change that here.

My suggestion for your case would be to write a wrapper for ->getMock() or another helper that checks if the class exists and errors out if it doesn't. That way you can avoid those issues down the line.

Also related: sebastianbergmann/phpunit-mock-objects#12

Hope thats fine and thanks a lot for taking the time to write the report but we can't change that for BC reasons :)

@edorian edorian closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.