trilopin / pt_mock
PHP测试的简单模拟
dev-master
2015-03-07 20:23 UTC
Requires
- php: >=5.3
- sebastian/comparator: 1.*
Requires (Dev)
- fabpot/php-cs-fixer: dev-master
- phpunit/phpunit: 4.*
This package is not auto-updated.
Last update: 2024-09-28 16:51:45 UTC
README
pt_mock
这个类适用于PHP >= 5.3.6。运行测试时,需要phpunit。
这个类提供了在测试时模拟对象的方法。可以简单地模拟基于参数的方法调用返回数据。也可以通过抛出异常来代替返回数据。
源代码在 [https://github.com/gramos74/pt_mock]
示例
我们有一个方法类,它接收一个对象作为参数。在这个方法中,我们将调用对象的'method_mock'方法,并传递参数'a',我们期望它返回'b'。
class class_a { function my_method(class_b) { return class_b->method_mock('a'); } } $class_b = new \Pt\Mock('Class B'); $class_b->expects('method_mock')->with('a')->returns('b'); $class_a = new class_a(); echo $class_a->my_method($class_b); // ----> 'b'
为了检查所有期望是否都已实现
$class_b->verify(); // for a instance of pt_mock
\Pt\Mock::verifyAll(); // for all mocks instantiated
如果你想测试该方法是否被调用两次
$class_b->expects('method_mock')->with('a')->times(2)->returns('b');
有时你不想测试方法是否被调用,你只想确保如果方法被调用,模拟对象将基于参数返回一个值。
$class_b->stubs('method_mock')->with('a')->returns('b'); echo $class_b->method_mock('a') ---> 'b' echo $class_b->method_mock('a') ---> 'b' echo $class_b->method_mock('a') ---> 'b' echo $class_b->method_mock('a') ---> 'b'
有时你希望抛出一个异常而不是返回数据。
$class_b->stubs('method_mock')->with('a')->raises(new Exception());
echo $class_b->method_mock('a') ---> raises a exception
鸣谢
非常感谢Mathias Biilmann [http://mathias-biilmann.net/] 提出的原始想法。一起工作的经历非常棒!
许可协议
版权所有 (c) 2011。在MIT许可协议下发布(见MIT-LICENSE)。Gabriel Ramos gabi@gabiramos.com