phpeclipsewordpresstestingsimpletest

PHP - Simpletest - How to test “included” classes


QUESTION

I'm trying to write test for changes to code for a Wordpress plugin.

<?php
require_once('.\simpletest\autorun.php');
require_once('.\wp-content\plugins\appointment-booking\includes.php'); 
// The line above causes [No runnable test cases in...] problem. 
// In my actual code, I have absolute path and I've made sure that the path is correct.

class test extends UnitTestCase 
{
 function test_pass()
 {
    $this->assertFalse(false);
 }
}
?>

Please help me understand why and how to fix. As stated in the comment, the second require_once causes error [No runnable test cases in...]

For example:

Bad TestSuite [test.php] with error [No runnable test cases in [test.php]]

I expect to not see the Bad TestSuite error. I expect for it to be able to run the test, as it can do when the second require_once is commented out.

I see this exact problem described here: PHP - Simpletest - How to test "included" classes, but I don't understand the problem, or how to fix. Thank you.

ANSWER 3/25/2016

Since I couldn't get this question to be taken off of "on-hold" status, and couldn't find a way to answer the question. I'm writing the solution here instead.

get_home_path() from Vincent's answer helped me to find the reason, so I marked it as answer although it's not really, technically. When I tried to use it in my code, I couldn't - the function name, and ABSPATH, etc. wasn't defined. The reason is that it wasn't considered to be part of WordPress.

Further searching found https://stackoverflow.com/a/27514259/5885721 And debugging saw that the WordPress file I wanted to include had this code

<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

Thus, that's why when the require function was ran, it stopped everything, and no tests was found. To fix, add

require( dirname( __FILE__ ) . '/wp-blog-header.php' ); 

instead of the second require_once and the ABSPATH will be set properly and I can use WordPress API and the plugin's code and write test cases.


Solution

  • It's dangerous to use absolute path. You can use :

    require_once(get_home_path() .'wp-content\plugins\appointment-booking\includes.php');
    

    (if you are in Windows environment)