I'm trying to get my head around PHP namespaces and testing with PHPUnit.
These tests from Codewars pass when I run phpunit test.php
in the command line on Windows:
<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;
class myTests extends TestCase {
public function testExamples() {
$this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
$this->assertEquals(pair_sum([1,2,3,1],3),1);
$this->assertEquals(pair_sum([1,3,2,2],4),2);
$this->assertEquals(pair_sum([1],4),false);
$this->assertEquals(pair_sum([2,3,10,-5],5),2);
}
}
However, when I comment out use PHPUnit\Framework\TestCase;
I get Class 'TestCase' not found
which makes sense since there is no reference to the needed classes/functions.
What's confusing me though is that lots of answers here on SO about namespacing claim that the use
keyword is NOT a substitute for include/require
and that the classes still need to be included/autoloaded(?).
I'm not using any autoloading here - just a solution.php
file and the tests above in a test.php
file.
Can someone please explain what I'm missing here? How come the tests work without any explicit including of the PHPunit functionality?
I should mention that I have PHPUnit installed globally via Composer.
Use vs Include in PHP
if you want to useuse
in the right way, you have to work with anautoloader
for loading the class.use
is for getting an shorthand in the current script. That has nothing to do with include. You can also doclass myTests extends \PHPUnit\Framework\TestCase {
phpunit
, which has already loaded all the relevant PHPUnit files.use
didn't load the file,phpunit
did.Can someone please explain what I'm missing here?
@deceze hits the nail. Scripts running viaphpunit
are not working as inphp
.