Hoping someone can help explain this before my mind melts. I'm trying to write unit tests for my Snippets using the PHPUnit framework
I can reproduce the problem using a very simple Snippet:
MyTestSnippet:
$x = $modx->getOption('x',$scriptProperties,'default value');
return $x;
I can easily add this to a page and then view the page and see the expected result (e.g. "default value");
But when I set this up in a unit test, I keep getting fatal errors because the $modx object is apparently not initialized, e.g.
PHP Fatal error: Call to a member function getOption() on a non-object in
/path/to/core/cache/includes/elements/modsnippet/556.include.cache.php on line 8
My testing code is pretty simple, but the testMySnippet function always fails.
<?php
class snippetTest extends \PHPUnit_Framework_TestCase {
// Must be static because we set it up inside a static function
public static $modx;
/**
* Load up MODX for our tests.
* Create sample data for testing.
*/
public static function setUpBeforeClass() {
$docroot = '/set/up/magically/elsewhere';
include_once $docroot . '/config.core.php';
if (!defined('MODX_API_MODE')) {
define('MODX_API_MODE', true);
}
include_once MODX_CORE_PATH . 'model/modx/modx.class.php';
self::$modx = new \modX();
self::$modx->initialize('mgr');
}
public function testMySnippet() {
$props = array();
$actual = self::$modx->runSnippet('MyTestSnippet', $props);
$expected = 'default value';
$this->assertEquals($expected, $actual);
}
Has anyone done this successfully? I had no idea I would be bashing my brains out all weekend for what I thought would take a few minutes.
Using Revo 2.2.14-pl