1

I've got a set of classes I'm trying to test. Class A depends on Class X. Class X contains functions which do random things and things with databases. I've created a mock version of Class X which returns exactly what I want it to in order to test Class A without dependencies.

So, my question is, how do I now test Class X as I've already included the mock version, which has the same name and filename. I get the "Cannot redeclare Class X" error.

I don't think I can use stubs as there's no way to pass the stubbed object into my class under test. The class under test (Class A) will ask for an instance of a static class (ClassA::getInstance();).

Is this going to be something to do with test suites or test cases as I can't un-include a the file which contains the mock version of Class X.

Thanks in advance for your help,

Mike

2 Answers 2

1

You can't uninclude files/classes in PHP, so the classes will either need to use different names or you will need to namespace them. As for using a stub class, two approaches you could use are. Use an instance/class variable that contains dependancies, so you can swap them out. Like

self::$_classes['classA']::methodCall();
$this->_classes['classA']::methodCall();

This will let you change the class dependancies at runtime if you really need statics. The other approach is to not use static classes and use a dependancy injection container like one found in symfony components. An injection container would let you inject mocks as needed as well.

Sign up to request clarification or add additional context in comments.

Comments

0

there's no way to pass the stubbed object into my class under test.

This means that your Class A strongly references Class X ? Personally I'd recommend to rename your Class X mockup to a real mockup (e.g. X_MockUp) put it in a test folder hierarchy and then pass it to the Class A that you want to test. It might be not possible at the moment, but then change your architecture! It will be more flexible and testable-friendly.

You get this error as you have the same class name in two files you are forced to differentiate them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.