I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working. When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this -
/src
MyClass.java
/test
MyClassTest.java
and so on.
When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes? So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.
-
You need to modify PHP's include_path so that it knows where to find MyClass.php when you
include()
it in your unit test.You could have something like this at the top of your test file (preceding your include):
set_include_path(get_include_path() . PATH_SEPARATOR . "../src");
This appends your
src
directory onto the include path and should allow you to keep your real code separate from your test code. -
I think it's a good idea to keep your files separate. I normally use a folder structure like this:
/myapp/src/ <- my classes /myapp/tests/ <- my tests for the classes /myapp/public/ <- document root
In your case, for including the class in your test file, why not just pass the the whole path to the include method?
include('/path/to/myapp/src/MyClass.php');
or
include('../src/MyClass.php');
-
I put my test cases next the the source in a file with the same name but a .phpt extension. The deployment script simply filters out *.phpt when they push to production.
-
Brian Phillips's answer does not go quite far enough, in my experience. You don't know what the current directory is when your tests are run by PHPUnit. So you need to reference the absolute path of the test class file in your set_include_path() expression. Like this:
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . "/../src");
This fragment can be placed in its own header file SetupIncludePath.php and included in test files with a 'require_once', so that test suites don't append the path multiple times.
0 comments:
Post a Comment