Jeff Puckett II Jeff Puckett II - 1 year ago 55
PHP Question

How to determine which assertion failed in a loop?

I have a PHPUnit test that loops through an array of invalid values, and asserts that each one is correctly rejected by the function.

For instance,

should return true only if the input is a string, else return false.

public function testValidateInput()
$obj = new MyClass();
$data = [
array('key' => 'value'),
(object) 'value'

foreach ($data as $item){
$this->assertSame(false, $obj->validateInput($item));

When the test fails an assertion, I only get the line number - which is the same for all the values because it's in a loop.

1) MyClassTest::testValidateInput
Failed asserting that true is identical to false.


How can I determine which value failed the assertion?


Use a data provider. PHPUnit will then tell you what index of the provider failed.

 * @dataProvider getInputData
public function testValidateInput($value)
  $obj = new MyClass();

  $this->assertSame(false, $obj->validateInput($value));

public function getInputData()
    return [
      [array('key' => 'value')],
      [(object) 'value'],

1) Test::testValidateInput with data set #3 (21.21)
Failed asserting that true matches expected false.

Also a hint: when asserting for boolean, use assertFalse method