I am looking at PHPUnit and the following has me wondering. Does or doesn't PHPUnit handle int. 1's and 0's as boolean? In my current testing, it doesn't.
Example: $this->assertTrue(preg_match('/asdf/', 'asdf'));
In my testing this fails, as preg_match() is returning int 1 or 0 and only bool false if there is an error.
I take it the following works, obviously, since comparisons always return bool. $this->assertTrue(preg_match('/asdf/', 'asdf') === 1);
Am I missing something in my preg_match, or my assertion to make it.... less strict?
EDIT: Does assertTrue require types to match? Is there any way to make the assertion less strict?
PHP has separate boolean
type, its values of TRUE
and FALSE
(case-insensitive constants) are not identical to integer values of 1 and 0.
When you use strict comparison (===
), it does not work: TRUE !== 1
and FALSE !== 0
.
When you use type juggling, TRUE
is converted to 1 and FALSE
is converted to 0 (and, vice versa, 0 is converted to FALSE
, any other integer is converted to TRUE
). So, TRUE == 1
and FALSE == 0
.
In PHPUnit, assertTrue
and assertFalse
are type-dependent, strict checks. assertTrue($x)
checks whether TRUE === $x
, it is the same as assertSame(TRUE, $x)
, and not the same as assertEquals(TRUE, $x)
.
In your case, one possible approach would be to use explicit type casting:
$this->assertTrue((boolean)preg_match('/asdf/', 'asdf'));
However, PHPUnit happens to have dedicated assertion for checking string against regular expression:
$this->assertRegExp('/asdf/', 'asdf');