【问题标题】:php cannot find class in same namespacephp 在同一命名空间中找不到类
【发布时间】:2017-10-04 05:31:32
【问题描述】:

我只是无法弄清楚我的 phpunit 测试在同一命名空间中找不到类的原因。

composer.json

"autoload": {
    "psr-4": {
        "LeonLombard\\OandaApi\\": ["src"]
    }
},
"autoload-dev": {
    "psr-4": {
        "LeonLombard\\OandaApi\\": ["tests"]
    }
},

src/OandaApi.php

<?php namespace LeonLombard\OandaApi;

class OandaApi
{
}

测试/OandaApiTest.php

<?php namespace LeonLombard\OandaApi;

class OandaApiTest extends \PHPUnit_Framework_TestCase
{
    public function testGetAnInstrumentListWithDefaultOptions()
    {
        $oandaApi = new OandaApi();
    }
}

tests/phpunit.xml

<phpunit
    bootsrap="../vendor/autoload.php"
>
    <testsuites>
        <testsuite name="All Tests">
            <directory>./</directory>
        </testsuite>
    </testsuites>
</phpunit>

这是我运行phpunit --config tests/phpunit.xml时遇到的错误:

致命错误:在第 7 行的 /Users/leonlombard/Sites/oanda-api/tests/OandaApiTest.php 中找不到类 'LeonLombard\OandaApi\OandaApi'

任何想法将不胜感激。我看过其他具有类似设置的帖子,但不明白为什么他们的帖子会起作用,而我的则不起作用。

谢谢。

【问题讨论】:

    标签: php namespaces phpunit


    【解决方案1】:

    您能否在 src/tests/ 中添加 / composer.json

    的 psr-04 中的 em> 目录

    在 composer.json 中

    之前

    "autoload": {
        "psr-4": {
            "LeonLombard\\OandaApi\\": ["src"]
        }
    },
    "autoload-dev": {
        "psr-4": {
            "LeonLombard\\OandaApi\\": ["tests"]
        }
    },
    

    之后

    "autoload": {
        "psr-4": {
            "LeonLombard\\OandaApi\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "LeonLombard\\OandaApi\\": "tests/"
        }
    },
    

    我认为它适合你。 以下是链接,请访问 that.it 对您有帮助。 https://getcomposer.org/doc/04-schema.md#psr-4

    谢谢。

    【讨论】:

    • 感谢您的建议。但是,我确实尝试过,但没有奏效。也请阅读该链接,以确保我没有遗漏对 PSR-4 的理解。
    • 我删除了所有代码并从头开始一步一步地开始,现在它正在工作。不确定我错过了什么,但可以确认 Brijesh 的建议是好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2012-05-27
    • 2017-12-21
    • 2017-05-01
    • 1970-01-01
    • 2022-11-10
    • 2015-05-28
    相关资源
    最近更新 更多