首页 > 解决方案 > PHPUnit:测试参数类型

问题描述

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

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

标签: phpunit-testingphpunit

解决方案


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

推荐阅读