如何测试Magento Block

时间:2012-09-23 15:15:26

标签: magento singleton phpunit

我想测试一个Magento块功能。我不知道,如何调用.phtml文件之外的函数。是否有人知道像getModel()这样的函数用于块?

我找到了

  

getBlockSingleton()

但是,它已被弃用,我无法让它发挥作用。

2 个答案:

答案 0 :(得分:7)

假设你的Magento root是你的web root。在Magento根目录中,创建一个 test.php 文件。您可以通过http:// base_url /test.php访问它。

ini_set('display_errors',true); //PHP has such friendly errors, show them!

include 'app/Mage.php';         //include the helper class/bootstrap file
Mage::setIsDeveloperMode(true); //flag to render Magento's traces

Mage::app();
/**
   Instantiate the app. Note that this is different from Mage::run()! This can
   be skipped given the Mage::app() call below.
*/

//block "type"
$class = 'core/bar';

//block instance
$block = Mage::app()->getLayout()->createBlock($class);

if (is_object($block)) die("Okay! ".get_class($block));

/**
 * If script execution reaches this point, there is one of
 * two problems:
 *
 * 1) bad/missing config
 * 2) bad path based on filename
 */

//the xpath which is used
$xpath = 'global/blocks/'.strstr($class,'/',true).'/class';

//a node from config XML (we hope)
$node = Mage::getConfig()->getNode($xpath);

//error condition 1:
if (!$node) die("Bad xpath, check configuration: ".$xpath);

//error condition 2:
$name = uc_words((string) $node . '_' . substr(strrchr($class, '/'), 1));
$file = str_replace('_', DIRECTORY_SEPARATOR, $name.'.php');
$issue = '<br /><br />';

if (!is_readable($file)) {
    //no file matching classname
    $issue .= "No file found for $file, tried:<pre> - ";
    $issue .= str_replace(PATH_SEPARATOR,'/'.$file.'<br /> - ',get_include_path()).$xpath.'</pre>';
} else {
    $issue .= "Wrong class name in $file";
}

echo sprintf('Xpath ok, looking for class <span style="font-family: Courier New">%s</span>%s',$name,$issue);

答案 1 :(得分:3)

如果您只需要块实例本身来测试方法,则可以执行以下功能:

/**
 * Create block instance for given block classAlias.
 *
 * @param string $classAlias Magento class alias for this block, e.g. 'catalog/product_price'
 *
 * @return Mage_Core_Block_Abstract
 */
public static function getBlockInstance($classAlias)
{
    $className = Mage::getConfig()->getBlockClassName($classAlias);
    $result = new $className;
    return $result;
}