开发者

PHPUnit Test Suite - Cannot redeclare class Mocking & Concrete classes

开发者 https://www.devze.com 2023-04-12 18:27 出处:网络
Here is my problem. I have a test suite that is testing a few classes. My classes all use dependency injection.

Here is my problem.

I have a test suite that is testing a few classes. My classes all use dependency injection.

I have a class called scheduleHandler that passes all tests. Then my other class ruleHandler has a method that requires an instance of scheduleHandler. I dont want to pass in the real scheduleHandler so I tried开发者_如何转开发 to create a mock scheduleHandler to inject in.

The problem I have is that because the scheduleHandler class is tested in the suite above ruleHandler, when the mock is created I get:-

PHP Fatal error:  Cannot redeclare class scheduleHandler

If I dont use a test suite, and run the tests individually everything is fine.

Anyone know of a way to get round this ?


My best guess so far:

var_dump(class_exists('scheduleHandler', false)); 

returns false for you. That means the class doesn't exist yet. Now if you autoloader doesn't find the class when phpunit is trying to extend from it phpunit will create the class it's self.

If you later down the road then require the REAL class from somewhere those to classes will collide.

To test this make sure you have required your REAL scheduleHandler class BEFORE creating the mock object.


Try using namespaces in Mock creation. If you don't use them in your project code then hopefully it will override global namespace and not cause conflict

$this->getMock('\SomeTestingFramework\SomeTestClass\scheduleHandler');


Try $this->getMock('scheduleHandler', array(), array(), '', false). That will cause PHPUnit to skip calling scheduleHandler::__construct, which probably caused the error by loading a class twice.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号