0

I'm just starting out learning PHPUnit. I have a seemingly very simple test;

namespace stats\Test;

use stats\Fetch;

class FetchTest extends \PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        $this->fetch = new Fetch;
    }

    public function testStoresListOfAssets()
    {
        $this->assertClassHasStaticAttribute('paths', 'Fetch'); //line 17
    }

}

My Fetch class is;

namespace stats;

class Fetch
{
    public static $paths = array(
        'jquery' => 'http://code.jquery.com/jquery.js'
    );
}

The error I get when running PHPUnit; PHPUnit_Framework_Exception: Argument #2 (string#Fetch)of PHPUnit_Framework_Assert::assertClassHasStaticAttribute() must be a class name

It's probably something very silly but I can't understand the problem

mikelovelyuk
  • 4,042
  • 9
  • 49
  • 95

2 Answers2

1

The PHPUnit_Framework_Assert use the PHP method class_exists to check if the classname you have indicated is correct (check this link to see the full code):

if (!is_string($className) || !class_exists($className, FALSE)) {
  throw PHPUnit_Util_InvalidArgumentHelper::factory(2, 'class name');
}

The problem you have here is the method class_exists doesn't take into account this command:

use stats\Fetch;

So that, you have to indicate the full path to make it work. In this link of stackoverflow you can find more information about that problem. You should change your assert to something like this:

$this->assertClassHasStaticAttribute('paths', '\\stats\\Fetch');

Community
  • 1
  • 1
Miguel
  • 1,361
  • 1
  • 13
  • 24
  • I stumbled on this answer myself about 30 seconds ago. I just tried `'stats\Fetch'` and it worked. Thanks for providing a correct answer though – mikelovelyuk Nov 06 '15 at 12:05
0

You're not supplying the fully qualified class name and in the context of assertClassHasStaticAttribute() or any other method/function outside of the scope of your (test) class the use statement that complements the class name.

If you're using PHP 5.5 or later (which you should ;) use Fetch::class.

In general you should prefer ::class over strings for class names as modern IDEs can help you with refactoring when changing class names which is close to impossible if you use strings.

To sum it up, for your example it would be:

public function testStoresListOfAssets()
{
    $this->assertClassHasStaticAttribute('paths', Fetch::class);
}
Michael D.
  • 96
  • 1
  • 5