PHP 单元 | assertContainsOnlyInstancesOf()函数
assertContainsOnlyInstancesOf()函数是 PHPUnit 中的内置函数,用于断言数组以包含其所有值作为给定类的实例。如果数组包含给定类的唯一实例,则此断言将返回 true,否则返回 false。如果为真,则断言的测试用例通过,否则测试用例失败。
句法:
assertContainsOnlyInstancesOf( string $classname, array $array, string $message = '' )
参数:此函数接受三个参数,如上述语法所示。参数说明如下:
- $classname:此参数是一个字符串,它是类的名称。
- $array:这个参数是一个数组,断言函数将检查它是否只包含给定类的实例。
- $message:此参数采用字符串值。当测试用例失败时,此字符串消息显示为错误消息。
下面的程序说明了 PHPUnit 中的 assertContainsOnlyInstancesOf()函数:
方案一:
php
assertContainsOnlyInstancesOf(
Foo::class,
[new Foo, new Bar, new Foo],
"testArray doesn't contains only instance of Foo"
);
}
}
?>
php
assertContainsOnlyInstancesOf(
Foo::class,
[new Foo, new Foo],
"testArray contains only instance of Foo"
);
}
}
?>
输出:
PHPUnit 8.2.5 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 81 ms, Memory: 10.00 MB
There was 1 failure:
1) GeeksPhpunitTestCase::testNegativeTestcaseForAssertContainsOnlyInstancesOf
testArray doesn't contains only instance of For
Failed asserting that Array &0 (
0 => Foo Object &00000000051a5c33000000005d98efba ()
1 => Bar Object &00000000051a5d77000000005d98efba ()
2 => Foo Object &00000000051a5c32000000005d98efba ()
) contains only values of type "Foo".
/home/shivam/Documents/geeks/phpunit/abc.php:20
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
方案二:
PHP
assertContainsOnlyInstancesOf(
Foo::class,
[new Foo, new Foo],
"testArray contains only instance of Foo"
);
}
}
?>
输出:
PHPUnit 8.2.5 by Sebastian Bergmann and contributors.
. 1 / 1 (100%)
Time: 67 ms, Memory: 10.00 MB
OK (1 test, 1 assertion)
注意:要使用 phpunit 运行测试用例,请按照此处的步骤操作。此外,phpunit 7 及更高版本支持 assertContainsOnlyInstancesOf()。