How to use assertions in PHPUnit tests?

Member

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

How to use assertions in PHPUnit tests?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a year ago

@lottie 

To use assertions in PHPUnit tests, you can follow these steps:

  1. Create a new test class that extends the PHPUnitFrameworkTestCase class. For example:
1
2
3
4
5
use PHPUnitFrameworkTestCase;

class MyTest extends TestCase {
    // ...
}


  1. Within your MyTest class, write test methods to test specific parts of your code. Each test method should be prefixed with the word test. For example:
1
2
3
public function testAddition() {
    // ...
}


  1. Use various assertion methods provided by PHPUnit to make assertions about your code's behavior. Some commonly used assertion methods include:
  • assertEquals($expected, $actual): Asserts that two values are equal. For example: $this->assertEquals(2, 1 + 1);
  • assertTrue($condition): Asserts that a condition is true. For example: $this->assertTrue(is_array([]));
  • assertFalse($condition): Asserts that a condition is false. For example: $this->assertFalse(empty([1, 2, 3]));
  • assertNull($value): Asserts that a value is null. For example: $this->assertNull($emptyVariable);
  • assertInstanceOf($expected, $actual): Asserts that an object is an instance of a specific class. For example: $this->assertInstanceOf(MyClass::class, $object);
  1. Modify your test methods to call the appropriate assertion methods to verify your code's behavior. For example:
1
2
3
4
public function testAddition() {
    $result = 1 + 1;
    $this->assertEquals(2, $result);
}


  1. Run your PHPUnit tests by executing the phpunit command in your project's root directory. PHPUnit will automatically discover your test classes and execute the test methods.


That's it! You can use various assertion methods provided by PHPUnit to make different types of assertions in your tests and ensure that your code behaves as expected.