繁体   English   中英

PHPUnit,接口和命名空间(Symfony2)

[英]PHPUnit, Interfaces and Namespaces (Symfony2)

我目前正在为Symfony2开发一个开源软件包,并且真的希望它在单元测试覆盖率和一般可靠性方面成为狗nadgers,但是由于我缺乏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失败,说明找不到类...

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

尝试

->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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM