2014-11-24 55 views
0

我正在使用CakePHP-ReST-DataSource-Plugin数据源在我的模型中打击RESTful服务。这意味着模型不会有数据库连接。在模型TestCase中为CakePHP模拟REST数据源

我已经成功地访问了服务,现在想写模型的单元测试。这被证明是一项艰巨的任务,因为我无法成功模拟数据源,因此我没有打到实际的远程服务,而是返回测试结果。

<?php 

    App::uses('KnowledgePoint', 'Model'); 

    class KnowledgePointTest extends CakeTestCase{ 
    public $fixtures = array('app.knowledgepoint'); 
    public $useDbConfig = 'RestTest'; 
    private $KnowledgePoint; 


    public function setUp() { 
     parent::setUp(); 
     $this->KnowledgePoint = ClassRegistry::init('KnowledgePoint'); 

     /** 
     * This is the confusing part. How would I mock the datasource 
     so that I can mock the request method which returns the data 
     from the api? 
     */ 
     $this->KnowledgePoint->DataSource = $this->getMockForModel(
      'RestSource',array('request')); 
    } 

    public function tearDown() { 
     parent::tearDown(); 
    } 
} 

我想能够嘲笑数据源和存根请求方法返回通常会被从远程服务返回的数据。

亲切的问候,

罗兰

+0

检查核心是如何做到的:** https://github.com/cakephp/cakephp/blob/2.5.6/lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php#L110** – ndm 2014-11-25 01:29:50

+0

我试着嘲笑它的核心做法,但我不断收到TestSource模拟找不到的错误。 – Awemo 2014-11-25 13:23:23

+0

核心测试也失败了吗? – ndm 2014-11-25 13:26:41

回答

2

嘲讽模型及其getDataSource()方法,以便它返回你的嘲笑数据源理论上应该工作。这里有一个例子

App::uses('RestSource', 'Rest.Model/Datasource'); 

$DataSource = $this->getMock('RestSource', array('request'), array(array())); 
$DataSource 
    ->expects($this->any()) 
    ->method('request') 
    ->will($this->returnValue('some custom return value')); 

$Model = $this->getMockForModel('KnowledgePoint', array('getDataSource')); 
$Model 
    ->expects($this->any()) 
    ->method('getDataSource') 
    ->will($this->returnValue($DataSource)); 

$Model->save(/* ... */); 

如果你想知道的array(array())为数据源模拟,为RestSource构造函数不为第一个参数(与父类的构造)提供一个默认值,这是必需的。

+0

已成功实施此解决方案以避免触碰远程服务。谢谢你的帮助。 – Awemo 2014-11-26 09:47:20