【问题标题】:Mock controller in Symfony2 unit testSymfony2 单元测试中的模拟控制器
【发布时间】:2014-07-30 04:27:16
【问题描述】:

我正在为 Symfony2 项目中的 API 服务编写单元测试。一种服务方法将控制器实例作为参数,并处理请求的 JSON。

    public function getJSONContent(Controller $controller) {
        $version = $this->getAPIVersion();

        //Read in request content
        $content = $controller->get("request")->getContent();
        if (empty($content)) {
            throw new HttpException(400, 'Empty request payload');
        }


        //Parse and Detect invalid JSON
        $jsonContent = json_decode($content, true);
        if($jsonContent === null) {
            throw new HttpException(400, 'Malformed JSON content received');
        }

        return $jsonContent;
    }

以下是我的测试:

class ApiTest extends \PHPUnit_Framework_TestCase {
    public function testGetJSONContent() {

        // Create a stub for the OrgController Object
        $stub = $this->getMock('OrganizationController');

        // Create the test JSON Content
        $post = 'Testy Test';
        $request = $post;
        $version = "VersionTest";
        $APIService = new APIService();

        // Configure the Stub to respond to the get and getContent methods
        $stub->expects($this->any())
             ->method('get')
             ->will($this->returnValue($post));

        $stub->expects($this->any())
             ->method('getContent')
             ->will($this->returnValue($request));

        $stub->expects($this->any())
             ->method('getAPIVersion')
             ->will($this->returnValue($version));


        $this->assertEquals('Testy Test', $APIService->getJSONContent($stub));
    }
}

我的测试抛出以下错误:

传递给 Main\EntityBundle\Service\APIService::getJSONContent() 的参数 1 必须是 Symfony\Bundle\FrameworkBundle\Controller\Controller 的实例,给定的 Mock_OrganizationController_767eac0e 的实例。

我的存根显然没有欺骗任何人,有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: unit-testing symfony phpunit


    【解决方案1】:

    使用命名空间来指定你要模拟的控制器。即

        // Create a stub for the OrgController Object
        $stub = $this->getMock('Acme\AcmeBundle\Controller\OrganizationController');
    

    【讨论】:

    • 谢谢,这让我摆脱了错误。我在声明测试之前使用了 require_once(filepath) 。不幸的是,我的嘲笑行为现在被忽略了,我必须解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2015-03-15
    • 2012-08-01
    • 2014-01-16
    相关资源
    最近更新 更多