PHPUnit 测试套件 - 无法重新声明类 Mocking &具体类
这是我的问题。
我有一个测试套件正在测试几个类。我的类都使用依赖注入。
我有一个名为 ScheduleHandler 的类,它通过了所有测试。然后我的另一个类ruleHandler 有一个需要scheduleHandler 实例的方法。我不想传递真正的scheduleHandler,所以我尝试创建一个模拟scheduleHandler来注入。
我遇到的问题是,因为scheduleHandler类在ruleHandler上面的套件中进行了测试,所以当创建模拟时,我得到:-
PHP Fatal error: Cannot redeclare class scheduleHandler
如果我不要使用测试套件,并单独运行测试一切都很好。
有人知道有办法解决这个问题吗?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
到目前为止我最好的猜测是:
为您返回
false
。这意味着该类还不存在。现在,如果当 phpunit 尝试扩展该类时,自动加载器找不到该类,那么 phpunit 将创建它自己的类。如果您稍后需要从某个地方获取 REAL 类,那么这些类将会发生冲突。
要测试这一点,请确保您在创建模拟对象之前需要真正的
scheduleHandler
类。My best guess so far:
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.尝试在模拟创建中使用命名空间。如果您不在项目代码中使用它们,那么希望它会覆盖全局命名空间并且不会导致冲突
$this->getMock('\SomeTestingFramework\SomeTestClass\scheduleHandler');
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');
尝试
$this->getMock('scheduleHandler', array(), array(), '', false)
。这将导致 PHPUnit 跳过调用scheduleHandler::__construct
,这可能是由于两次加载类而导致错误。Try
$this->getMock('scheduleHandler', array(), array(), '', false)
. That will cause PHPUnit to skip callingscheduleHandler::__construct
, which probably caused the error by loading a class twice.