douzhuican0041 2017-07-09 22:24
浏览 55
已采纳

PHPUnit确保特性满足接口

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?

  • 写回答

1条回答 默认 最新

  • dtpoius74857 2017-07-09 22:50
    关注

    How about just creating the class as a test asset:

    namespace Foo\Bar\Test\Asset;
    
    use Psr\Log;
    
    final class LoggerAware implements Log\LoggerAwareInterface
    {
        use Log\LoggerAwareTrait;
    }
    

    And then asserting it implements the interface:

    namespace Foo\Bar\Test;
    
    use PhpUnit\Framework;
    use Psr\Log;
    
    final class LoggerAwareTest extends Framework\TestCase
    {
        public function testImplementsLoggerAwareInterface()
        {
            $loggerAware = new Asset\LoggerAware();
    
            $this->assertInstanceOf(Log\LoggerAwareInterface::class, $loggerAware);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?