【问题标题】:phpunit test and namespacesphpunit 测试和命名空间
【发布时间】:2018-07-29 00:44:46
【问题描述】:

我有

错误:找不到类“app\Main”

我不知道怎么解决?

我使用 PHPSTORM 和 phpunit 最新版本。

Structure of my directories

Main.php

<?php
namespace app;

class Main
{
    public function Calc()
    {
        return 1;
    }
}

MainTest.php

<?php

namespace app;

use PHPUnit\Framework\TestCase;

class MainTest extends TestCase
{
    public function testCalc()
    {
        $a = new Main();
    }
}

phpunit.xml:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit verbose="true">
    <testsuites>
        <testsuite name="My Test Suite">
            <directory suffix="Test.php" phpVersion="5.3.0" phpVersionOperator=">=">tests</directory>
           <!-- <file phpVersion="5.3.0" phpVersionOperator=">=">/path/to/MyTest.php</file>-->
        </testsuite>
    </testsuites>
</phpunit>

composer.json

{
  "autoload": {
    "classmap": [
      "src/"
    ]
  },
  "require": {
    "phpunit/phpunit": "7.0.1"
  }
}

【问题讨论】:

标签: php namespaces phpunit


【解决方案1】:

您需要告诉自动加载器在哪里可以找到类的 php 文件。这是通过遵循 PSR-0 标准来完成的。

将此添加到您的 composer.json:

{
   ...
     "autoload": {
      "psr-0": { "": "tests/app/" }
   }
}

现在自动加载器可以找到你需要的类,让 PHPunit 在运行测试之前知道有一个文件要执行:一个引导文件。 但是,最好使用 PHPunit 配置文件:

  <!-- /phpunit.xml.dist -->
  <?xml version="1.0" encoding="utf-8" ?>
  <phpunit bootstrap="./vendor/autoload.php">

    <testsuites>
        <testsuite name="The project's test suite">
            <directory>./tests/app</directory>
        </testsuite>
    </testsuites>

</phpunit>

【讨论】:

  • 没有。我有 php 7.1
【解决方案2】:

我想我解决了。也许是 app 目录中的“app”命名空间和 test/app 之间的冲突。它现在工作。 我将应用程序中的命名空间更改为“框架”并将其添加到 composer.json

   "autoload": {
        "psr-4": {
            "framework\\": "app"
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-20
    • 2017-11-27
    • 2011-12-30
    • 2015-11-13
    • 2013-10-26
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多