Coe*_*ens 6 phpunit unit-testing cakephp behavior mocking
我刚开始在CakePHP进行单元测试(耶!)并遇到了以下挑战.希望有人可以帮助我:-)
我的模型使用行为在本地保存后将更改发送到API.我想假装在测试期间对API进行的所有调用(这些将单独测试)以节省API服务器的负载,更重要的是,实际上不保存更改:-)
我正在使用CakePHP 2.4.1.
该文章的代码如下:
$provider = $this->getMock('OurProvider', array('getInfo'));
$provider->expects($this->any())
->method('getInfo')
->will($this->returnValue('200'));
Run Code Online (Sandbox Code Playgroud)
这可能是错误的方向,但我认为这可能是一个良好的开端.
有效地:一段代码,用于演示如何在CakePHP模型中模拟行为以进行单元测试.
也许这个问题会导致添加CakePHP手册作为额外的奖励,因为我觉得它在那里缺失.
在此先感谢您的努力!
我发现了这个相关的问题,应该回答这个问题(部分).无需模拟API,而是可以创建模型将使用的行为测试.
我想弄清楚BehaviorTest应该是什么样子.
AD7*_*six 10
与许多类一样,行为将使用类名作为键添加到类注册表中,以及后续请求从classregistry加载的同一对象.因此,模拟行为的方法只是在使用它之前将其放入类注册表中.
完整示例:
<?php
App::uses('AppModel', 'Model');
class Example extends AppModel {
}
class TestBehavior extends ModelBehavior {
public function foo() {
throw new \Exception('Real method called');
}
}
class BehaviorExampleTest extends CakeTestCase {
/**
* testNormalBehavior
*
* @expectedException Exception
* @expectedExceptionMessage Real method called
* @return void
*/
public function testNormalBehavior() {
$model = ClassRegistry::init('Example');
$model->Behaviors->attach('Test');
$this->assertInstanceOf('TestBehavior', $model->Behaviors->Test);
$this->assertSame('TestBehavior', get_class($model->Behaviors->Test));
$this->assertSame(['foo' => ['Test', 'foo']], $model->Behaviors->methods());
$model->foo();
}
public function testMockedBehavior() {
$mockedBehavior = $this->getMock('TestBehavior', ['foo', 'bar']);
ClassRegistry::addObject('TestBehavior', $mockedBehavior);
$model = ClassRegistry::init('Example');
$model->Behaviors->attach('Test');
$this->assertInstanceOf('TestBehavior', $model->Behaviors->Test);
$this->assertNotSame('TestBehavior', get_class($model->Behaviors->Test));
$expected = [
'foo' => ['Test', 'foo'],
'bar' => ['Test', 'bar'],
'expects' => ['Test', 'expects'], // noise, due to being a mock
'staticExpects' => ['Test', 'staticExpects'], // noise, due to being a mock
];
$this->assertSame($expected, $model->Behaviors->methods());
$model->foo(); // no exception thrown
$mockedBehavior
->expects($this->once())
->method('bar')
->will($this->returnValue('something special'));
$return = $model->bar();
$this->assertSame('something special', $return);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2755 次 |
| 最近记录: |