Search code examples
laravelannotationsphpunit

@beforeClass annotation on Laravel testcase method ignored


In my Laravel 5.1 app's base TestCase which extends Illuminate\Foundation\Testing\TestCase I have this method:

/**
 * @beforeClass
 */
public function resetDatabase()
{
    echo "I never see this message\n";
    $this->artisan("migrate:refresh");
}

Other @before and @after annotations in that class is honoured as advertised. Why is this method not called in my unit tests?


Solution

  • It turned out that all annotations are not equal!

    Inspecting vendor/phpunit/phpunit/src/Util/Test.php shows:

    private static function isBeforeClassMethod(ReflectionMethod $method)
    {
        return $method->isStatic() && strpos($method->getDocComment(), '@beforeClass') !== false;
    }
    
    
    private static function isBeforeMethod(ReflectionMethod $method)
    {
        return preg_match('/@before\b/', $method->getDocComment());
    }
    

    So, if I make the function static it is recognised and runs before the class tests. The @before annotation examples that are around were all instance methods, so this lead to the confusion.