脚本宝典收集整理的这篇文章主要介绍了php – 如何抢先模拟由另一个类实例化的类,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要为一个类编写一个测试,它会导致第三方库被实例化.我想模拟/存储库类,以便它不会进行实时API调用.
我在CakePHP v3.x框架中使用PHPunIT.我能够模拟库并创建存根响应,但这并不妨碍“真实”类被我的测试之外的代码实例化.我考虑过试图在实例化的上游模拟类,但是有很多类,这会使得测试难以置信地编写/维护.
以下是PHPunit.de网站的示例(第9章):
public function testObserversAreUpdated() { // Create a mock for the Observer class,// only mock the update() method. $observer = $this->getMockBuilder('Observer') ->setMethods(array('update')) ->getMock(); // Set up the expectation for the update() method // to be called only once and with the string 'something' // as its parameter. $observer->exPEcts($this->once()) ->method('update') ->with($this->equalTo('something')); // Create a Subject object and attach the mocked // Observer object to it. $subject = new Subject('My subject'); $subject->attach($observer); // Call the DOSomething() method on the $subject object // which we expect to call the mocked Observer object's // update() method with the string 'something'. $subject->doSomething(); }
如果API返回了某些内容,那么您可以将will()添加到第二个语句,如下所示:
->will($this->returnValue(TRUE));
以上是脚本宝典为你收集整理的php – 如何抢先模拟由另一个类实例化的类全部内容,希望文章能够帮你解决php – 如何抢先模拟由另一个类实例化的类所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。