PHP 7.2的非井形成数值遇到测试失败,但为什么呢?
问题描述:
确定,所以这是与开始以数字串仅失败一个简单的单元测试。PHP 7.2的非井形成数值遇到测试失败,但为什么呢?
我的原班在这里
class InstanceID implements InstanceIDInterface
{
private $id;
public function __construct(int $id)
{
$this->id = $id;
}
}
这里是单元测试
class InstanceIDTest extends \PHPUnit_Framework_TestCase
{
public function testCanInitializeWithValidID()
{
$InstanceID = new InstanceID(3456);
$this->assertInstanceOf('InstanceID', $InstanceID);
}
/**
* @dataProvider invalidStrings
*/
public function testNonNumericStringShouldNotBeAccepted($id)
{
$this->expectException(TypeError::class);
$InstanceID = new InstanceID($id);
}
public function invalidStrings() {
return [
["ABC1234"], // works
["1234WUK"], // error
["W1234W"], // works
["1234yHk92383"] // error
];
}
}
,这是试运行结果
There were 2 errors:
1) InstanceIDTest::testNonNumericStringShouldNotBeAccepted with data set #1 ('1234WUK')
A non well formed numeric value encountered
2) InstanceIDTest::testNonNumericStringShouldNotBeAccepted with data set #3 ('1234yHk92383')
A non well formed numeric value encountered
问题是为什么错误不是通过 $这个 - > expectException(类型错误::类)被抓; 线?
答
因为它不是一个例外,而是一个通知。
为了它,你需要启用严格类型的
declare(strict_types=1);
你InstanceID
文件的顶部检查TypeError
。
现在所发生的事情是 - "1234WUK"
被隐式转换为1234
整数的通知书。