質問

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');

他のヒント

Please do not use a bunch of assertTrue or assertFalse checks with the real logic embedded in a complicated function call when there are more specific test functions available.

PHPUnit has a very vast set of assertions that are really helpful in the case they are not met. They give you a bunch of context of what went wrong, which aids you in debugging.

To check for a regular expression, use assertRegExp() (see http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions.assertRegExp)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top