iTranslated by AI
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
<?php
namespace Sample;
function sampleMethod(): bool
{
return true;
}
Test Code
<?php
namespace Tests;
use function Sample\sampleMethod;
use PHPUnit\Framework\TestCase;
class SampleTest extends TestCase
{
public function testSampleMethod(): void
{
$this->assertTrue(sampleMethod());
}
}
Autoload Configuration
{
// 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.
{
"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.
Discussion