【问题标题】:PHPUnit fails in Netbeans with NamespacesPHPUnit 在具有命名空间的 Netbeans 中失败
【发布时间】:2011-11-14 17:02:43
【问题描述】:

我有:PHP 5.3.8、PHPUnit 3.5.15、Netbeans 7.0.1

在使用 Netbeans 的标准示例进行 PHPUnit 测试时,它运行良好。 通过仅添加“命名空间测试;”我得到 Calculator.php 不是文件也不是目录的错误。如何解决这个问题呢? (我想在我的项目中使用命名空间声明)

要测试的类:

namespace test;

class Calculator {

/**
 * @assert (0, 0) == 0
 * @assert (0, 1) == 1
 * @assert (1, 0) == 1
 * @assert (1, 1) == 2
 * @assert (1, 2) == 4
 */
public function add($a, $b) {
    return $a + $b;
}

}

?>

单元测试:

require_once dirname(__FILE__) . '/../Calculator.php';

/**
 * Test class for Calculator.
 * Generated by PHPUnit on 2011-09-11 at 00:52:24.
 */
class CalculatorTest extends PHPUnit_Framework_TestCase {

/**
 * @var Calculator
 */
protected $object;

/**
 * Sets up the fixture, for example, opens a network connection.
 * This method is called before a test is executed.
 */
protected function setUp() {
    $this->object = new Calculator;
}

/**
 * Tears down the fixture, for example, closes a network connection.
 * This method is called after a test is executed.
 */
protected function tearDown() {

}

/**
 * Generated from @assert (0, 0) == 0.
 */
public function testAdd() {
    $this->assertEquals(
            0, $this->object->add(0, 0)
    );
}

/**
 * Generated from @assert (0, 1) == 1.
 */
public function testAdd2() {
    $this->assertEquals(
            1, $this->object->add(0, 1)
    );
}

/**
 * Generated from @assert (1, 0) == 1.
 */
public function testAdd3() {
    $this->assertEquals(
            1, $this->object->add(1, 0)
    );
}

/**
 * Generated from @assert (1, 1) == 2.
 */
public function testAdd4() {
    $this->assertEquals(
            2, $this->object->add(1, 1)
    );
}

/**
 * Generated from @assert (1, 2) == 4.
 */
public function testAdd5() {
    $this->assertEquals(
            4, $this->object->add(1, 2)
    );
}

}

?>

【问题讨论】:

    标签: php netbeans namespaces phpunit


    【解决方案1】:

    @Tomasz 的答案当然是正确的。作为一个小插件:

    据我了解,将测试放在与生产类相同的命名空间中已成为一种常见做法。

    namespace test;
    require_once dirname(__FILE__) . '/../Calculator.php';
    
    class CalculatorTest extends \PHPUnit_Framework_TestCase {
    

    那么你可以继续使用

    $this->object = new Calculator:
    

    【讨论】:

    • +1 啊,这是我的问题:超类之前的反斜杠。 \PHPUnit_FrameworkTestCase 解决了。也有道理。
    【解决方案2】:

    了解如何在代码中使用命名空间类。您需要创建 Calculator 类实例,而不是:

    $this->object = new Calculator;
    

    但是:

    $this->object = new \test\Calculator;
    

    我假设该类已加载。如果没有看到您的自动加载器或正确的文件路径。

    【讨论】:

    • 工作就像一个魅力,谢谢 Tomasz(我还不得不从单元测试中删除命名空间)
    猜你喜欢
    • 2010-11-18
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2021-05-13
    • 1970-01-01
    • 2018-07-29
    • 2018-01-12
    相关资源
    最近更新 更多