【问题标题】:PHPUnit, Interfaces and Namespaces (Symfony2)PHPUnit、接口和命名空间 (Symfony2)
【发布时间】:2011-12-30 13:36:50
【问题描述】:

我目前正在为 Symfony2 开发一个开源包,并且真的希望它在单元测试覆盖率和一般可靠性方面成为狗的麻烦,但是由于我缺乏 PHPUnit 知识,我遇到了障碍(或者一个复杂的场景,谁知道)..

目前,我有一个 Mailer 类,用于处理单个邮件场景。有点像这样:

<?php
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;

class Mailer
{
    protected $mailer;
    protected $router;
    protected $templating;
    protected $parameters;

    public function __construct($mailer, RouterInterface $router, EngineInterface $templating, array $parameters)
    {
        $this->mailer = $mailer;
        $this->router = $router;
        $this->templating = $templating;
        $this->parameters = $parameters;
    }
}

很简单,里面有一些 Symfony2 接口 gubbins 来处理不同的路由和模板系统,快乐快乐快乐快乐。

这是我尝试为上述设置的初始测试:

<?php
use My\Bundle\Mailer\Mailer

class MailerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructMailer
    {
        $systemMailer = $this->getSystemMailer();
        $router = $this->getRouter();
        $templatingEngine = $this->getTemplatingEngine();

        $mailer = new Mailer($systemMailer, $router, $templatingEngine, array());
    }

    protected function getSystemMailer()
    {
        $this->getMock('SystemMailer', array('send');
    }   
    protected function getRouter()
    {
        $this->getMock('RouterInterface', array('generate');
    }

    protected function getTemplatingEngine()
    {
        $this->getMock('RouterInterface', array('render');
    }
}

这里的问题是我的模拟对象没有实现 Symfony\Bundle\FrameworkBundle\Templating\EngineInterface 和 Symfony\Component\Routing\RouterInterface,所以我不能使用我自己创建的任何模拟对象。我尝试过的一种方法是在测试页面上创建一个实现正确接口的抽象类,但是 getMockForAbstractClass 失败,说明它找不到该类...

【问题讨论】:

    标签: php symfony tdd phpunit


    【解决方案1】:

    在模拟时,您需要使用完全限定的类路径,因为模拟功能没有考虑调用代码的命名空间或任何“使用”语句。

    试试

    ->getMock('\\Symfony\\Component\\Routing\\RouterInterface'); 
    

    并省略第二个参数。通常,指定方法的作用比好的要糟糕得多。 仅当您希望所有其他方法都像以前一样工作时,才需要第二个参数。

    示例

    <?php
    
    namespace bar;
    
    class MyClass {}
    
    namespace foo;
    
    use \bar\MyClass;
    
    class MockingTest extends \PHPUnit_Framework_TestCase {
    
        public function testMock() {
            var_dump($this->getMock('MyClass') instanceOf MyClass);
            var_dump($this->getMock('\\bar\\MyClass') instanceOf MyClass);
        }   
    }
    

    生产:

    /phpunit.sh --debug fiddleTestThree.php 
    PHPUnit @package_version@ by Sebastian Bergmann.
    
    
    Starting test 'foo\MockingTest::testMock'.
    .bool(false)
    bool(true)
    

    【讨论】:

    • 啊,当我尝试这样做时,我从一开始就错过了斜线>_
    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2010-11-18
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多