PHPUnit Mock 对象在默认情况下从不期望 [英] PHPUnit Mock Objects never expect by default

查看:55
本文介绍了PHPUnit Mock 对象在默认情况下从不期望的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有正式定义的期望,有没有办法告诉 phpunit 模拟对象永远不要期望方法调用?

Is there a way to tell a phpunit mock object to never expect the method calls if there are no formally defined expectations for them?

推荐答案

在我看来,永远不要对每种方法都抱有期望是不明智的.所以 phpunit 没有任何功能.只有当您想完全确保某些方法不会被调用时,才应该使用从不"期望.

In my opinion it's not got idea to never expectation for every method. So phpunit doesn't have any functionality. Can should use "never" expectations only if you want totally ensure that some method won't be called.

无论如何,您可以使用一些匹配器来更接近您的目标.示例:

Anyway you can use some matchers to get closer your goal. Examples:

从不期望所有对象的方法(如果调用任何模拟方法失败):

Never expectations for all object's methods (fails if any of mocked methods will be called):

$mock->expects($this->never())
    ->method($this->anything());

因此,例如,您可以测试某些对象除了已测试的方法之外不会调用任何方法:

So, for example you can test that some object won't call any method apart from tested one:

$mock = $this->getMock('Some\Tested\Class', array('testedMethod'));
$mock->expects($this->never())
    ->method($this->anything());

您也可以尝试使用其他匹配器,例如.matchesRegularExpression:

You can try also with another matcher, eg. matchesRegularExpression:

$mock->expects($this->never())
    ->method($this->matchesRegularExpression('/get.*/'));

例如,如果调用任何 getter,上面的示例将失败.

For example above will fail if any getter will be called.

我知道这不是您想要的,但恐怕 phpunit 没有这样的解决方案.

I'm aware this is not exactly what You want, but I'm afraid there is no such solution with phpunit.

这篇关于PHPUnit Mock 对象在默认情况下从不期望的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆