Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: Trying to @cover or @use not existing method

I'm learning how to unit test with PHPUnit 4.3.5 / PHP 5.5.14. All went fine until I tried to get my code coverage. I'm receiving this error: "Trying to @cover or @use not existing method "MyClass::__construct" when trying to get code coverage. I tried other SO answers but couldn't fix it. Any ideas what am i doing wrong? Thanks!

/**
 * Test constructor.
 * @covers MyClass::__construct
 * @group MyClassTest
 */
public function test_Can_Create_MyClass_Instance() {
    $this->assertInstanceOf('MyClass', $this->_myClass);
}
like image 985
MrTourkos Avatar asked Dec 22 '14 15:12

MrTourkos


2 Answers

You can get the same error if you expect the @covers annotation to work with the namespace use operator.

The following code will not work:

<?php

namespace MyCompany\MyBundle\Test\UnitTest\Service;

use MyCompany\MyBundle\Service\ClassToTest;

class MyAwesomeTest
{
    /**
     * @covers ClassToTest::someMethod()
     */
    public function testSomeMethod()
    {
        // do your magic
    }
}

Smart IDEs like PHPStorm solve the ClassToTest::someMethod() annotation if you CTRL+click it but PHPUnit will give you a Trying to @cover or @use not existing method "ClassToTest::someMethod". error.

There's a pull request for this here: https://github.com/sebastianbergmann/phpunit/pull/1312

As a work around just use the full class name:

<?php

namespace MyCompany\MyBundle\Test\UnitTest\Service;

use MyCompany\MyBundle\Service\ClassToTest;

class MyAwesomeTest
{
    /**
     * @covers \MyCompany\MyBundle\Service\ClassToTest::someMethod()
     */
    public function testSomeMethod()
    {
        // do your magic
    }
}
like image 141
Francesco Casula Avatar answered Oct 05 '22 19:10

Francesco Casula


If your class does implement the __construct method, then the problem is that the class itself is not found. Start removing the @covers annotation, and check if the class can be loaded. For example try: var_dump(class_exists('MyClass')); inside the test (before the assert that I presume won't pass).

In annotations, and in general when passing your class name as a string, you should always refer to the class using its full namespaced name:

\MyClass
\MyNamespace\MyClass
like image 31
gontrollez Avatar answered Oct 05 '22 19:10

gontrollez