How to test for inequality in PHPUnit?

Member

by domenico , in category: PHP General , a year ago

How to test for inequality in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , a year ago

@domenico 

In PHPUnit, you can use the assertNotEquals() or assertNotSame() methods to test for inequality.

  1. Use assertNotEquals() to test if two values are not equal:
1
$this->assertNotEquals($expected, $actual);


Here, $expected is the expected value and $actual is the value that is being tested. The assertion will pass if the two values are not equal.

  1. Use assertNotSame() to test if two objects or values are not the same:
1
$this->assertNotSame($expected, $actual);


Similarly, $expected is the expected object or value, and $actual is the value being tested. The assertion will pass if the two objects or values are not the same.


Example usage:

1
2
3
4
5
6
7
// Test for inequality with assertNotEquals
$this->assertNotEquals(5, 10);  // Passes
$this->assertNotEquals('abc', 'abc');  // Fails

// Test for inequality with assertNotSame
$this->assertNotSame($obj1, $obj2);  // Passes
$this->assertNotSame(5, 5);  // Fails


You can also provide an optional custom message as the last argument to these methods to provide additional information about the assertion:

1
2
$this->assertNotEquals($expected, $actual, 'The values should not be equal');
$this->assertNotSame($expected, $actual, 'The objects should not be the same');


Note that these methods are available as part of the PHPUnitFrameworkTestCase class, so make sure your test class extends this class.