iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐙

Troubleshooting Custom Function Testing in PHPUnit

に公開

The Issue

When I tried to test a custom function using PHPUnit, I encountered an error stating that the function was not defined.

Error: Call to undefined function Sample\sampleMethod()

Custom Function

src/Sample.php
<?php

namespace Sample;

function sampleMethod(): bool
{
    return true;
}

Test Code

tests/SampleTest.php
<?php

namespace Tests;

use function Sample\sampleMethod;
use PHPUnit\Framework\TestCase;

class SampleTest extends TestCase
{
    public function testSampleMethod(): void
    {
        $this->assertTrue(sampleMethod());
    }
}

Autoload Configuration

composer.json
{
  // Omitted
  "autoload": {
    "psr-4": {
      "Sample\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\\": "tests/"
    }
  }
  // Omitted
}

The Cause

The target for automatic loading in PSR-4 is "classes," and files that are not classes are not loaded.

Since the sample.php created this time was not in the "class" format specified by PSR-4, it was not loaded during the test execution. As a result, sampleMethod() became an undefined function, which led to the error.

The Solution

I was able to load the file by specifying the path to the target file in the files key of the autoload property.

Always run composer dump-autoload after adding the entry.

composer.json
{
  "autoload": {
    "psr-4": {
      "Sample\\": "src/"
    },
    "files": ["src/sample.php"] // Added
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\\": "tests/"
    }
  }
}

Conclusion

Since my previous tests always targeted classes, this issue had never occurred. Moving forward, I want to be more conscious of using tools with a solid understanding of how they work.

References

PSR-4: Autoloader

GitHubで編集を提案

Discussion