Reputation: 841
Is there a way to make PHPUnit throw an exception if a method being stubbed does not originally exist in the class being stubbed?
Here's a crude example:
class User {
function getId() { ... }
}
class LoginTest extends PHPUnit_Framework_TestCase {
function testLogin() {
...
$userMock = $this->getMockBuilder('User')
->setMethods(['getID']) // getId is misspelled; error should occur
->getMock();
...
}
}
class Login {
function login($user) {
...
$id = $user->getID(); // tests will pass even though this is misspelled
...
}
}
Upvotes: 1
Views: 731
Reputation: 3967
@Schleis is right that you cannot do it in PHPUnit directly. But as of PHPUnit 4.5 you can use Prophecy to create test doubles. Prophecy will not tolerate this behavior. You won't be able to mock a non-existing method with it.
Upvotes: 2
Reputation: 43800
No, you can't.
PHPUnit doesn't need to have the class available to mock it. And you can even set the mock to not use any autoloading. When this happens, PHPUnit creates a fake class on the fly. This fake class doesn't have any defined methods which would cause an exception to be thrown, failing your tests suite.
Your tests should fail because of issues with the code that is being tested. Issues with the mock are outside of the scope of your test. The issue in your example would be caught during your functional testing.
There really isn't an easy way to tell between an misspelled function and one that hasn't been implemented yet.
Upvotes: 1