php - MockBuilder 在接口中看不到方法
问题描述
我正在尝试模拟 Throwable 接口,但 MockBuilder 没有看到 getPrevious() 方法。
$throwableMock = $this->getMockBuilder(\Throwable::class)
->disableOriginalConstructor()
->getMock();
$throwableMock->method('getPrevious')
->willReturn($domainExceptionMock);
我收到此错误:
Trying to configure method "getPrevious" which cannot be configured because it does not exist, has not been specified, is final, or is static
如果我将 addMethods 添加到模拟生成器,如下所示:
$throwableMock = $this->getMockBuilder(\Throwable::class)
->addMethods(['getPrevious'])
->disableOriginalConstructor()
->getMock();
我收到以下错误:
Trying to set mock method "getPrevious" with addMethods(), but it exists in class "Throwable". Use onlyMethods() for methods that exist in the class
我究竟做错了什么?
解决方案
我不确定您要对模拟异常做什么,但您可能会发现构建一个真实对象更容易,然后抛出它:
class SanityTest extends TestCase
{
public function testThrowingMock(): void
{
$domainExceptionMock = new \RuntimeException('hello');
$exception = new \Exception('msg', 0, $domainExceptionMock);
$tst = $this->createMock(Hello::class); // class Hello {public function hello() {} }
$tst->method('hello')
->willThrowException($exception);
try {
$tst->hello();
} catch (\Exception $e) {
$this->assertInstanceOf(\RuntimeException::class, $e->getPrevious());
}
}
}
模拟一切可能比设置和使用,和/或事后检查真实对象更困难。
推荐阅读
- python - 计算返回时操作数类型错误
- ssh - 无法通过 SSH 克隆 gitlab 项目
- python-3.x - 如何使用 Python 生成唯一值列表以用作 MySql 数据库的主键?
- api - Wealthfront 与外部账户连接背后的技术
- python - 在 Python 中,我可以从另一个对象创建或继承一个对象,而不会丢失或覆盖旧对象中先前存在的属性吗?
- postgresql - 如何在 Postgress PGadmin 4 编辑器中设置变量?
- python - 如何在 unittest 和 pytest 中访问这些模拟
- sql - Snowflake 根据不同列值的组合返回记录一次
- c# - 正则表达式 - 获取冒号后的数字
- c# - 我的第二个表单没有显示,但是里面的代码被执行了