【问题标题】:Autoloading class files for PHPUnit为 PHPUnit 自动加载类文件
【发布时间】:2020-04-13 19:25:09
【问题描述】:

所以,我只是在玩 PHPUnit,我真的不需要它,但我想了解它是如何工作的,所以我在我的插件中的一个随机类上尝试它。 我遇到的问题是,每当我运行phpunit 时,我都会说在我的测试中找不到Plot 类。在我的 composer.json 文件中,我有

{
    "require": {
        "phpunit/phpunit": "^8.5"
    },

    "autoload":{
        "psr-4" : { "\\mohagames\\PlotArea\\utils\\" : "src/mohagames/PlotArea/utils/"}
    }
}

我的 Plot.php 文件位于 C:\Users\moham\Documents\GitHub\PlotArea\src\mohagames\PlotArea\utils\ 目录中,并具有 mohagames\PlotArea\utils 命名空间

但由于某种原因它仍然说

C:\Users\moham\Documents\GitHub\PlotArea>C:\Users\moham\Documents\Github\PlotArea\vendor\bin\phpunit --debug
PHPUnit 8.5.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.3.4
Configuration: C:\Users\moham\Documents\GitHub\PlotArea\phpunit.xml

Test 'SampleTest::testPlot' started
Test 'SampleTest::testPlot' ended


Time: 95 ms, Memory: 4.00 MB

There was 1 error:

1) SampleTest::testPlot
Error: Class 'Plot' not found

C:\Users\moham\Documents\GitHub\PlotArea\tests\unit\SampleTest.php:8

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

还有 SampleTest 测试类:

<?php

use PHPUnit\Framework\TestCase;

class SampleTest extends TestCase{

    public function testPlot(){
        $plot = new Plot();

    }
}

我在互联网上尝试了各种解决方案,但都没有奏效

【问题讨论】:

  • Plot 类的完整命名空间是什么?您尚未导入它(文件顶部带有“使用”,或 \with\a\fullpath\Plot)
  • 非常感谢!我真的不知道我是怎么忘记这样做的。

标签: php composer-php phpunit


【解决方案1】:

就像 Alister 指出的那样,首先导入类是有效的,否则 PHP 不知道代码指的是什么类。

<?php

use PHPUnit\Framework\TestCase;
use mohagames\PlotArea\utils\Plot;

class SampleTest extends TestCase{

    public function testPlot(){
        $plot = new Plot();

    }
}

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2014-10-02
    • 2017-06-13
    • 1970-01-01
    • 2012-02-13
    • 2021-06-18
    相关资源
    最近更新 更多