在phpunit中创建phpunit.xml文件

时间:2017-01-26 20:05:08

标签: php xml phpunit

我的项目有这样的结构:

  • 根 - / src - / tests

在src中我的文件是Task1.php。在tests文件夹中是我的测试文件。 例如:

<?php
require __DIR__ . '/../src/Task1.php';
class Task1Test extends PHPUnit_Framework_TestCase
 {
public function testTask1(){
    $this->assertEquals([1,1,1,3,5,9],fib([1,1,1],6));
}
}

我使用require __DIR__ . '/../src/Task1.php';包含我的src文件 我想添加 bootstrap.php 文件并在那里包含src文件。然后在phpunit.xml中添加bootstrap.php。

我的phpunit.xml:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" strict="true" bootstrap="bootstrap.php"></phpunit>

我应该在bootstrap.php文件中写什么?

我尝试在测试文件夹中添加Autoloader.php文件:

<?php
class AutoLoader {

static private $classNames = array();

/**
 * Store the filename (sans extension) & full path of all ".php" files found
 */
public static function registerDirectory($dirName) {

    $di = new DirectoryIterator($dirName);
    foreach ($di as $file) {

        if ($file->isDir() && !$file->isLink() && !$file->isDot()) {
            // recurse into directories other than a few special ones
            self::registerDirectory($file->getPathname());
        } elseif (substr($file->getFilename(), -4) === '.php') {
            // save the class name / path of a .php file found
            $className = substr($file->getFilename(), 0, -4);
            AutoLoader::registerClass($className, $file->getPathname());
        }
    }
}

public static function registerClass($className, $fileName) {
    AutoLoader::$classNames[$className] = $fileName;
}

public static function loadClass($className) {
    if (isset(AutoLoader::$classNames[$className])) {
        require_once(AutoLoader::$classNames[$className]);
    }
  }

 }

spl_autoload_register(array('AutoLoader', 'loadClass'));

在tests文件夹中的bootsstrap.php:

<?php
include_once('AutoLoader.php');
// Register the directory to your include files
AutoLoader::registerDirectory(__DIR__ . '/../src/');

但它不起作用

2 个答案:

答案 0 :(得分:0)

我为你刻了两个版本。

请参阅https://github.com/Grawer/starckoverflow-41881997

First(分支全局函数)是一个具有全局声明函数的版本,非常基本的函数。所做的工作基本上是words从包含测试的文件移到require,并且全部都是。

第二个版本(分支主机),自动加载器更复杂,我意识到你可以继续这样做。尽管如此,我仍坚持这样做。你快到了。您写bootstrap.phpcomposer.json中有一个拼写错误,它应该是prs-4。剩下的就是将自动加载器需求添加到psr-4,您还需要将bootstrap.php函数放在类中。然后您可以访问它,而无需在测试类文件中要求该类。

答案 1 :(得分:0)

如果您在使用自动加载器时遇到问题,并且测试不起作用,请尝试执行我所做的操作,并更改您的 composer.json

包括行:

"autoload": {
    "psr-4": {
      "foo\\": "foo"
    }
  },

foo 是命名空间。不同之处在于我使用的是 psr-0 而不是 psr-4。

立即工作!

相关问题