php - PHPUnit:测试参数类型
问题描述
我想测试一个可以将类实例Foo
或字符串作为参数的方法。如果传递了其他任何内容,它会抛出一个Exception
.
如果我没有通过其中一种有效类型,我该如何测试是否会引发异常?我如何确保除了其中一种类型之外的任何东西都会产生异常?
解决方案
要详细说明我对 OP 的评论 - 您可以expectException()
用来告诉 PHPUnit 您要断言在以下测试中引发了异常。请参阅https://phpunit.readthedocs.io/en/8.0/writing-tests-for-phpunit.html#testing-exceptions
例子:
public function testExceptionIsThrown()
{
$this->expectException(WhateverTheException::class);
$class = new ClassToTest;
$class->methodToTest(1); // an integer is not a string or an instance of Foo and should throw an exception
}
推荐阅读
- php - 如何根据 IF 条件运行多个查询?
- shell - 从命令行检查头文件 math.h 中有多少个例程
- ios - 如何在我的 AppDelegate.swift 中向 Workmanager 注册“特定插件”?
- datatable - 在 QTP/UFT 中的多行运行时添加数据
- python - Pytorch张量**2计算
- java - 在我在 mysql 中备份和恢复我的数据库后,我看不到我的 blob 文件
- python - 为什么 Counter.__iadd__ 比 Counter.update 慢这么多?
- python - 实例化动态类属性
- android - 导航中目的地之间的动画过渡
- android - 如何在 Edittext Android 上获取当前光标?