【问题标题】:PHPUnit: testing parameter types [duplicate]PHPUnit:测试参数类型
【发布时间】:2019-10-22 04:49:32
【问题描述】:

我想测试一个可以将Foo 类的实例或字符串作为参数的方法。如果传递了其他任何内容,则会抛出 Exception

如果我没有通过其中一种有效类型,我该如何测试是否会引发异常?我如何确保除了其中一种类型之外的任何东西都会产生异常?

【问题讨论】:

  • 添加对$this->expectException(WhateverTheException::class) 的调用并使用错误的参数类型调用您的方法。查看phpunit.readthedocs.io/en/8.0/…

标签: php unit-testing phpunit


【解决方案1】:

详细说明我对 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
}

【讨论】:

  • 我知道你的意思,我的测试有点像这样。但是如果我通过一个浮点数怎么办?还是布尔?还是其他类的实例?我想测试 any 其他数据类型。能做到吗?
  • 你的类方法中有这个逻辑吗?像if (!($value instanceof Foo || is_string($value))) { throw new \Exception('nope'); } 这样的东西,如果是这样,你真的不需要做更多的测试。只有几次失败和一次通过。
  • 是的,就是这样。谢谢。
猜你喜欢
  • 2013-08-12
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2012-07-01
  • 1970-01-01
  • 2019-11-17
相关资源
最近更新 更多