【问题标题】:Codeception unit test代码接收单元测试
【发布时间】:2017-11-07 06:37:56
【问题描述】:

我是 PHP 和 Codeception 以及单元测试整个概念的新手。到目前为止,我已经遵循 Codeception 的快速入门指南 (http://codeception.com/quickstart) 并阅读了他们的文档 (http://codeception.com/docs/05-UnitTests)。

我已经成功搭建了测试环境,并且

  1. 创建单元测试文件 (php codecept.phar generate:test unit ExampleTest)
  2. 运行测试命令(php codecept.phar run unit ExampleTest),返回错误:

有 1 个错误:

1) ExampleTest: Validation
 Test  tests\unit\ExampleTest.php:testValidation

 [Error] Class 'User' not found  

#1  ExampleTest->testValidation
#2  C:\laragon\www\kario\vendor\bin\codecept.phar:5

我不明白的是,测试文件如何知道要在哪个 PHP 文件上运行测试?

我的 laragon 项目名为kario,位于C:\laragon\www\kario\resources\views\pages\orders,而测试单元文件位于C:\laragon\www\kario\vendor\bin\tests\unit

【问题讨论】:

  • 您的应用程序代码中有自动加载功能吗?自动加载是您最好的选择,但如果您不使用它,那么您将不得不单独要求每个文件。

标签: php unit-testing codeception laragon


【解决方案1】:

我也有这个问题,并为自己找到了答案。在这里发布http://phptest.club/t/beginner-codeception-unit-test-help/1849,但也在这里:

首先,一些细节。我正在使用由 PHPUnit 7.1.4 提供支持的 Codeception v2.4.1。答案是:

codeception.yml 中,添加这两行:

    settings:
        bootstrap: _bootstrap.php

这里的_bootstrap.php 可以是您想要的引导文件名称。

您必须将_bootstrap.php 放置在以下每个目录中:

tests/unit/_bootstrap.php
tests/functional/_bootstrap.pp
tests/acceptance/_bootstrap.php

在我的tests/unit/_bootstrap.php 文件中,我放置了以下代码:

<?php
use Codeception\Util\Autoload;
Autoload::addNamespace('myclassnamespace', __DIR__ . '/../../Classes/');

为了确保我有正确的课程路径,我在我的_bootstrap.php 中使用了trigger_error(__DIR__),然后添加了Autoload 行。

然后在我的tests/unit/TestAddCest.php 中,我将以下行放在文件的开头:

<?php
use mynamespace;

在我的测试函数中看起来像这样(注意 User 类的实例化):

    public function tryToTest(UnitTester $I)
    {
      $user = new mynamespace\User('someusername');
      $I->assertEquals('someusername', $user->username);
    }

我手动键入了该函数,因为我与代码不在同一台机器上并且不想完成它,所以它可能有错字或错误,但你明白了。

编辑 05/01/2018: 其他人在 http://phptest.club 上回复了我:

最好在composer.json 中配置类的自动加载并让 Composer 完成其余的工作,除非您尽量避免使用 Composer。

https://getcomposer.org/doc/01-basic-usage.md#autoloading

【讨论】:

  • 我认为您的 Autoload::addNamespace() 路径将是 DIR 。 ‘\..\..\resources\views\pages\orders’
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 2016-09-18
  • 2014-03-23
相关资源
最近更新 更多