IT Share you

Composer 및 autoload.php를 사용하여 PHPUnit의 클래스 자동로드

shareyou 2020. 11. 30. 20:15
반응형

Composer 및 autoload.php를 사용하여 PHPUnit의 클래스 자동로드


Composer를 통해 Sebastian Bergmann의 PHPUnit 버전 3.7.19를 설치했고 단위 테스트를 원하는 클래스를 작성했습니다.

나는 각 단위 테스트에 자동으로 적재 내 모든 수업을하고 싶은 없이 사용할 필요 include또는 require내 테스트의 상단에 있지만이 어려운 것으로 증명!

내 디렉토리 구조는 다음과 같습니다 (후행 / 슬래시는 파일이 아니라 디렉토리를 나타냄).

  • composer.json
  • composer.lock
  • composer.phar
  • lib /
    • returning.php
  • 테스트 /
    • returningTest.php
  • 공급 업체 /
    • 큰 상자/
      • phpunit
    • 작곡가/
    • phpunit /
    • 심포니 /
    • autoload.php

composer.json 파일에는 다음이 포함됩니다.

"require": {
    "phpunit/phpunit": "3.7.*",
    "phpunit/phpunit-selenium": ">=1.2"
}

returning.php 클래스 파일에는 다음이 포함됩니다.

<?php
class Returning {
    public $var;
    function __construct(){
        $this->var = 1;
    }
}
?>

returningTest.php 테스트 파일에는 다음이 포함됩니다.

<?php
class ReturningTest extends PHPUnit_Framework_TestCase
{
    protected $obj = null;

    protected function setUp()
    {
        $this->obj = new Returning;
    }

    public function testExample()
    {   
        $this->assertEquals(1, $this->obj->var);
    }

    protected function tearDown()
    {

    }
}
?>

그러나 ./vendor/bin/phpunit tests명령 줄에서 실행 하면 다음 오류가 발생합니다.

PHP 치명적인 오류 : 8 행의 /files/code/php/db/tests/returningTest.php에서 클래스 '반환'을 찾을 수 없습니다.

파일 composer생성 했지만 이것이 내 문제와 관련이 있는지 확실하지 않습니다.autoload.phpvendor/autoload.php

또한 Stack Overflow에 대한 다른 답변에서 사람들은 composer에서 PSR-0사용 namespace하고 PHP 에서 명령을 사용하는 것에 대해 언급 했지만 둘 중 하나를 사용하는 데 성공하지 못했습니다.

도와주세요! PHPUnit에서 클래스를 자동로드하여 include또는 걱정하지 않고 객체를 생성하는 데 사용할 수 있습니다 require.


업데이트 : 2013 년 8 월 14 일

이제 프로젝트 에서 PHPUnit 테스트를 쉽게 시작하고 실행할 수 있도록 PHPUnit Skeleton 이라는 오픈 소스 프로젝트를 만들었 습니다.


글쎄, 처음에는. 클래스에 대한 php 파일을 찾을 위치를 오토로더에 알려야합니다. 이는 PSR-0 표준을 따라 수행됩니다.

가장 좋은 방법은 네임 스페이스를 사용하는 것입니다. 오토로더 Acme/Tests/ReturningTest.phpAcme\Tests\ReturningTest클래스 를 요청할 때 파일을 검색합니다 . 몇 가지 훌륭한 네임 스페이스 자습서가 있습니다. 검색하고 읽기만하면됩니다. 네임 스페이스는 자동 로딩을 위해 PHP에 포함 된 것이 아니라 자동 로딩에 사용할 수있는 것입니다.

Composer는 표준 PSR-0 오토로더 (에서 하나 vendor/autoload.php) 와 함께 제공됩니다 . 귀하의 경우 자동 로더에게 lib디렉토리 에서 파일을 검색하도록 지시하고 싶습니다 . 사용할 때 다음 ReturningTest이를 찾습니다 /lib/ReturningTest.php.

이것을 당신의 composer.json:

{
    ...
    "autoload": {
        "psr-0": { "": "lib/" }
    }
}

문서의 자세한 정보 .

이제 오토로더는 테스트를 실행하기 전에 실행할 파일 인 부트 스트랩 파일이 있음을 PHPunit에 알려주는 데 필요한 클래스를 찾을 수 있습니다. --bootstrap옵션을 사용하여 부트 스트랩 파일이있는 위치를 지정할 있습니다.

$ ./vendor/bin/phpunit tests --bootstrap vendor/autoload.php

그러나 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</directory>
        </testsuite>
    </testsuites>

</phpunit>

이제 명령을 실행할 수 있으며 자동으로 구성 파일을 감지합니다.

$ ./vendor/bin/phpunit

구성 파일을 다른 디렉토리에 넣는 경우 -c옵션 을 사용하여 명령에 해당 디렉토리의 경로를 입력해야합니다 .


[ Update2 ] 또 다른 간단한 대안 autoload-devcomposer.json( reference ) 지시문 을 사용하는 것 입니다. 장점은 서로 다른 클래스를 자동로드하기 위해 두 개의 bootstrap.php (프로덕션 용 하나, 개발 용 하나)를 유지할 필요가 없다는 것입니다.

{
  "autoload": {
    "psr-4": { "MyLibrary\\": "src/" }
  },
  "autoload-dev": {
    "psr-4": { "MyLibrary\\Tests\\": "tests/" }
  }
}

[ 업데이트 ] Wouter J의 답변이 더 완벽합니다. 그러나 내 tests/폴더에 PSR-0 자동로드를 설정하려는 사람들을 도울 수 있습니다 .
Phpunit은이 패턴을 가진 모든 파일을 스캔합니다 *Test.php. 따라서 자동으로로드 할 필요가 없습니다. 그러나 우리는 여전히 tests/fixture / stub 또는 일부 부모 클래스와 같은 다른 지원 클래스를 자동로드하려고합니다 .

쉬운 방법은 Composer 프로젝트 자체가 phpunit 테스트를 설정하는 방법을 보는 것입니다. 사실 아주 간단합니다. "bootstrap"이있는 줄에 유의하십시오.

참조 : https://github.com/composer/composer/blob/master/phpunit.xml.dist

<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="tests/bootstrap.php"
>
    <testsuites>
        <testsuite name="Composer Test Suite">
            <directory>./tests/Composer/</directory>
        </testsuite>
    </testsuites>

    <groups>
        <exclude>
            <group>slow</group>
        </exclude>
    </groups>

    <filter>
        <whitelist>
            <directory>./src/Composer/</directory>
            <exclude>
                <file>./src/Composer/Autoload/ClassLoader.php</file>
            </exclude>
        </whitelist>
    </filter>
</phpunit>

참조 : https://github.com/composer/composer/blob/master/tests/bootstrap.php

<?php

/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

error_reporting(E_ALL);

$loader = require __DIR__.'/../src/bootstrap.php';
$loader->add('Composer\Test', __DIR__);

위의 마지막 줄은 Composer \ Test 네임 스페이스 아래에 phpunit 테스트 클래스를 자동로드하는 것입니다.


None of these answers were what I was looking for. Yes PHPUnit loads test files, but not stubs/fixtures. Chaun Ma's answer doesn't cut it because running vendor/bin/phpunit already includes the autoload, so there's no way to get an instance of the autoloader to push more paths to it's stack at that point.

I eventually found this in the docs:

If you need to search for a same prefix in multiple directories, you can specify them as an array as such:

{
    "autoload": {
        "psr-0": { "Monolog\\": ["src/", "lib/"] }
    }
}

There is a really simple way to set up phpunit with autoloading and bootstap. Use phpunit's --generate-configuration option to create your phpunit.xml configuration in a few seconds-:

vendor/bin/phpunit --generate-configuration

(Or just phpunit --generate-configuration if phpunit is set in your PATH). This option has been available from version phpunit5 and upwards.

This option will prompt you for your bootstrap file (vendor/autoload.php), tests and source directories. If your project is setup with composer defaults (see below directory structure) the default options will be all you need. Just hit RETURN three times!

project-dir
   -- src
   -- tests
   -- vendor

You get a default phpunit.xml which is good to go. You can of course edit to include any specialisms (e.g. colors="true") you require-:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.1/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         executionOrder="depends,defects"
         forceCoversAnnotation="true"
         beStrictAboutCoversAnnotation="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutTodoAnnotatedTests="true"
         verbose="true">
    <testsuites>
        <testsuite name="default">
            <directory suffix="Test.php">tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
        </whitelist>
    </filter>
</phpunit>

If you are using PHPUnit 7 you can make your classes from src/ folder to autoload in tests like this:

  1. Ensure that your composer.json file looks similar to this:

    {
        "autoload": {
            "classmap": [
                "src/"
            ]
        },
        "require-dev": {
            "phpunit/phpunit": "^7"
        }
    }
    
  2. To apply changes in composer.json run command:

    composer install
    
  3. Finally you can run tests in tests/ folder:

    ./vendor/bin/phpunit tests/
    

참고URL : https://stackoverflow.com/questions/15710410/autoloading-classes-in-phpunit-using-composer-and-autoload-php

반응형