Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit Test Suite - Cannot redeclare class Mocking & Concrete classes

Tags:

php

phpunit

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 ?

like image 333
SteveG Avatar asked Oct 12 '11 15:10

SteveG


2 Answers

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.

like image 141
edorian Avatar answered Sep 20 '22 17:09

edorian


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');

like image 34
Artjom Kurapov Avatar answered Sep 21 '22 17:09

Artjom Kurapov