【问题标题】:How to get started with PHPUnit at the command line?如何在命令行开始使用 PHPUnit?
【发布时间】:2011-01-04 15:01:38
【问题描述】:

我有一个 MacBook Pro,安装了 PEAR,安装了 PHPUnit,所以我可以在命令行输入 phpunit 并得到使用帮助。

现在我想进行测试,以便我可以从那里构建。

我有一个名为 index.php 的文件,其中包含以下内容:

<?php

require_once '?????';


class Product {

    protected $id;

    public function __construct($id) 
    {
        $this->id = $id;
    }

    public function get_id()
    {
        return $this->id;
    }

}

class ProductTest extends PHPUnit_Framework_TestCase
{
    function testBasis()
    {
        $instance = new Product(1);

        $this->assertInstanceOf('Product',$instance);
        $this->assert($instance->get_id(), 1);
    }
}

在命令行中,我想进入文件所在的目录并输入如下内容:

phpunit ?????

接下来的步骤是什么,以便我能够从命令行使用 PHPUnit 测试上述类?

【问题讨论】:

  • 是的,这就是我正在阅读的文档(第 4 章),其中第 3 章展示了如何安装我所做的 pear/phpunit,第 4 章假设安装了其余部分,但是当我输入“ phpunit productTest”它找不到“./ProductTest.php”,当我输入“phpunit index.php”时,它说,“callt o undefined method ProductTest::assert()”,我需要一个基本的例子来工作我可以使用该文档。
  • 因为 assert 未定义,请查看第 21 章以查看所有可用功能(例如,看起来您在真正需要时尝试使用 assert 是 assertEquals() ,还有 assertInstanceOf()需要替换为 isInstanceOf() )

标签: php unit-testing phpunit


【解决方案1】:
  1. 如果您正确安装了 phpunit,则不需要包含行。
  2. class ProductTest extends PHPUnit_Framework_TestCase
  3. 保存文件ProductTest.php
  4. 在命令行使用“cd”浏览到保存 ProductTest.php 的目录
  5. 如果你正确安装了phpunit,你应该可以输入phpunit --verbose ProductTest.php

您的 ProductTest.php 文件必须如下所示:

<?php

class Product {

    protected $id;

    public function __construct($id) 
    {
        $this->id = $id;
    }

    public function get_id()
    {
        return $this->id;
    }

}

class ProductTest extends PHPUnit_Framework_TestCase
{
    function testBasis()
    {
        $instance = new Product(1);

        $this->isInstanceOf('Product',$instance);
        $this->assertEquals($instance->get_id(), 1);
    }
}

?>

在命令行运行phpunit --verbose ProductTest,会输出:

PHPUnit 3.4.13 by Sebastian Bergmann.

ProductTest
.

Time: 0 seconds, Memory: 6.50Mb

OK (1 test, 1 assertion)
dorin@ubuntu:/var/www$ phpunit --verbose ProductTest
PHPUnit 3.4.13 by Sebastian Bergmann.

ProductTest
.

Time: 0 seconds, Memory: 6.50Mb

OK (1 test, 1 assertion)

【讨论】:

  • 好的,我这样做了,它告诉我 PHP Fatal error: Call to undefined method ProductTest::assert() 告诉我它没有找到 PHPUnit_Framework_TestCase 或者可能是什么原因?
  • 复制我的确切代码,将其保存在一个名为 ProductTest.php 的文件中,您会看到所有测试都会通过。
  • 是的,它现在可以工作了,assert 和文件名是问题,谢谢
【解决方案2】:

我使用these instructions 将 phpunit 版本从 3.4 升级到 3.6,它解决了我的 assertInstanceOf 缺失函数问题。如果有人来这个帖子寻找同样的问题,应该考虑升级到最新版本的 phpunint 测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2017-10-05
    相关资源
    最近更新 更多