dimanche 9 juillet 2017

PHPUnit ensuring a trait satisfies an interface

Let's look at the code in Psr/Log, in particular:

As you know, a trait cannot implement an interface, so these two parts need a class to be successfully connected together.

Let's say I cover testing of the trait (it's relatively easy via PHPUnit's getMockForTrait). The next thing to test is that I want to prove that the trait satisfies the interface.

In terms of code, it looks simple enough:

public function testThatTraitSatisfiesInterface()
{
    $className = 'test_class_' . uniqid();
    $classCode = sprintf(
        'class %s implements %s { use %s; }',
        $className,
        LoggerAwareInterface::class,
        LoggerAwareTrait::class
    );

    eval($classCode); // ewww :see_no_evil:
    new $className(); // no errors? good, test successful
}

A have a few concerns here:

  • I'd like to avoid eval as much as possible (even if I know that it's what drives PHPUnit anyway), but..
  • I'd rather use PHPUnit's functionality if at all possible

So the big question is, are there any alternatives?

Aucun commentaire:

Enregistrer un commentaire